.
:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface NotAutowiredBean {
}
BeanFactoryPostProcessor:
import com.yaswanth.NotAutowiredBean;
import java.lang.reflect.Field;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanCreationNotAllowedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;
@Component
public class NotAutowiredBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
throws BeansException {
try {
String[] illegalAutowiredBeans = beanFactory
.getBeanNamesForAnnotation(NotAutowiredBean.class);
String[] allBeans = beanFactory.getBeanDefinitionNames();
for (String beanName : allBeans) {
String beanClassName = beanFactory.getBeanDefinition(beanName).getBeanClassName();
if (beanClassName != null) {
Class<?> clazz = Class.forName(beanClassName);
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(Autowired.class)) {
if (field.getType().isAnnotationPresent(NotAutowiredBean.class)) {
throw new BeanCreationNotAllowedException(beanName, "");
}
}
}
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Spring beans:
interface DefaultService {
}
@NotAutowiredBean
@Component
@Async
@ConditionalOnNotWebApplication
public class MyService1 implements DefaultService {
}
@NotAutowiredBean
@Component
@Async
@ConditionalOnWebApplication
public class MyService2 implements DefaultService {
}
@NotAutowiredBean. NotAutowiredBeanFactoryPostProcessor beans, , Autowired bean. NotAutowiredBean . , BeanCreationNotAllowedException, - .