//不自动注入 AbstractBeanDefinition.AUTOWIRE_NO //根据类型自动装配(但是这个类型是根据set***方法进行装配的) AbstractBeanDefinition.AUTOWIRE_BY_TYPE //根据名称自动装配 AbstractBeanDefinition.AUTOWIRE_BY_NAME //根据构造函数自动装配 AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR
默认为
@Repository public class UserDao1 { private BookDao1 bookDao1; public BookDao1 getBookDao1() { return bookDao1; } public void setBookDao1(BookDao1 bookDao1) { System.out.println("setBookDao1......."); this.bookDao1 = bookDao1; } } @Repository public class BookDao1 {
@Configuration @ComponentScan("com.tian") public class AppConfig { }
@Test public void test_auto(){ AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); System.out.println(context.getBean(UserDao1.class).getBookDao1()); }
public class MyImportRegistrar implements ImportBeanDefinitionRegistrar { @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { GenericBeanDefinition beanDefinition = (GenericBeanDefinition) registry.getBeanDefinition("userDao1"); //修改自动注入模型 beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE); registry.registerBeanDefinition("userDao1", beanDefinition); } }
public void setBookDao1(BookDao1 bookDao1) { }
参见:https://juejin.im/post/5d99fcc7e51d457822796ea1