spring4 知识点

1 bean的 创建
1,直接在配置文件里面写一个带有@Bean注解的方法(返回值就是那个bena对象),(name等于 方法名)
2,使用 FactoryBean 接口(三个方法分别是创建,类型,单例)(实测需要加入@Component)
3,在 配置类里面可以 用一个 @Bean 方法的形参里面写入Spring 容器里面的 Bean 对象

备注:使用 @Scope指定是不是单例(默认是单例)

2 指定bean 的 初始销毁方法
1 bean 类继承 ,InitializingBean,DisposableBean 接口实现对应方法
2, 在配置注解上面指定 @Bean(destroyMethod="destroy",initMethod="afterPropertiesSet")
3,(jsr 250 的 注解) 在方法前写上 @PreDestroy(销毁前) 和 @PostConstruct(创建以后)




spring bean属性的注入

3,多个类型 同类的 bean ,按照 类型获取的时候会获取代 @Primary 注解标注的那个


4 AnnotationConfigApplicationContext(Config.class,UserFactoryBean.class) 的 方法里面 不仅仅 可以写配置还可以写 带有注解的组件(@Component ,@servier @Controller @Repository,等等)


5 @Qualifier 对 @Autowired,@Inject(需要引入inject 包) 按照类型匹配进行修饰(按照名字选择)

备注:Qualifier 修饰也不管用 ,使用 @Resource(name='') 吧 实测 可以


@ComponentScan 指定扫描的包

6 拿到 spring 容器
1 实现 ApplicationContextAware 这个方法其实就是在 BeanPostProcessor 里面判断是否实现了 ApplicationContextAware 接口 ,若果实现了,娜美就掉指定方法设置 spring容器
2 构造方法的参数里面写 public SpringContext(ApplicationContext applicationContext,@Qualifier("user2") User user)
备注,这种方法只能有一个构造函数,多个不知道选那个,会默认选择无参数的那个 (如果没有无参数的那个会报错) spring 4.3 提供(spring4.3 默认会给会为 构造方法注入)
3 直接在任意spring 管理的类中注入 spring 容器 @Inject AnnotationConfigApplicationContext context;

4 不能通过getBean 的到


三个重要的接口


7 对spring 管理的 Bean 的管理
实现 BeanPostProcessor 的类可以对任何 spring管理的类的 初始化进行 管理
备注:我们可以通过 postProcessor 对server 类调用 做参数日志(返回一个代理对象,然后在方法调用前打印参数)

8 BeanFactoryPostProcessor 接口 可以拿到 所有bean 的 factroy 在 BeanPostProcessor 之前触发

9 BeanDefinitionRegistryPostProcessor 可以动态的注册spring 的 bean 对象 (BeanDefinitionRegistryPostProcessor 集成自 BeanFactoryPostProcessor 接口)


原文地址:https://www.cnblogs.com/cxygg/p/9291312.html