文章标题

来源:互联网 发布:java工程师培训机构 编辑:程序博客网 时间:2024/06/08 05:32

spring Bean
Bean的生命周期
1.初始化
实现org.springframework.beans.factory.InitializingBean接口,覆盖afterPropertiesSet方法
配置init-method

<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>public void init(){    //do some initialzation work    }    }
public class ExampleInitializingBean implements InitializingBean{@Overridepublic void afterPropertiesSet() throws Exception{//do something}}

2.销毁
实现org.springframework.beans.factory.DisposableBean接口,覆盖destroy方法
配置destroy-method

<bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="cleanup"/>public class ExampleBean(){public void cleanup(){    //do some destruction work    }    }
public class ExampleDisposableBean implements DisposableBean{@Overridepublic void destroy() throws Exception{//do something}}

配置全局默认初始化,销毁方法
这里写图片描述

Aware接口
Bean的自动装配(Autowiring)
种类:No; byname;byType;Constructor
Resources
这里写图片描述
ResourceLoader

public interface ResourceLoader{Resource getResource(String location);}
Resource template =ctx.getResource("some/resource/path/myTemplate.txt");Resource template =ctx.getResource("classpath:some/resource/path/myTemplate.txt");Resource template =ctx.getResource("file:/some/resource/path/myTemplate.txt");

Bean管理的注解实现
1.classpath扫描与组建管理
这里写图片描述
2.元注解
3.通过基于xml的spring配置如下标签;仅会查找在同一个applicationtext中的bean注解
4.@required 注解适用于bean属性的setter方法。仅仅表示受影响的bean属性必须在配置时被填充通过在bean定义或通过自动装配一个明确的属性值

public class SimpleMovieLister{private MovieFinder movieFinder;@requiredpublic void setMovieFinder(MovieFinder movieFinder){this.movieFinder=movieFinder;}}

5.@Autowired注解那些众所周知的解析依赖性接口,如BeanFactory,ApplicationContext,Environment,ResourceLoader,ApplicationEventPublisher.and MessageSource

public class MovieRecommender{@Autoworedpublic ApplicationContext context;public MovieRecommender(){}}

6.@Qualififier 按类型

原创粉丝点击