public class Person implements BeanNameAware, ApplicationContextAware,InitializingBean, BeanPostProcessor,DisposableBean{
String name;
@Autowired
Car car;
Person () {
name = "zhangsan";
}
public void custom_destroy() {}
@PostConstruct
public void postConstruct() {}
public void custom_init() {}
......
//省略@Override
}
----------
src/main/java/configure.xml配置文件:
<bean class="com.example.beanlife.BeanLifeCycle" init-method="custom_init" destroy-method="custom_destroy"></bean>
----------
pom.xml
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>application.properties</include>
<include>configure.xml</include>
</includes>
</resource>
</resources>
</build>
----------
主类:
@ImportResource(locations = "classpath:configure.xml")
----------
bean生命周期
- 调用Person的默认构造函数.
- IOC注入,即调用Car的构造函数生成一个bean, 注入到Person实例.
- setBeanName(String beanName)回调,可通过该方法从参数中获取到本bean在ApplicationContext中的beanName. //override
- setApplicationContext(ApplicationContext var1)回调,可以获取到通过参数传递的ApplicationContext,借此可进一步获取到ApplicationContext中的其它bean,以及容器中的所有其它信息。//override
- postConstruct()//@PostConstruct
- afterPropertiesSet() //override
- init-method //xml
- postProcessBeforeInitialization(Object var1, String var2) //override
- postProcessAfterInitialization(Object var1, String var2) //override
Bean可以使用了。 - destroy() //override
- custom_destroy() //xml
在pom中被include的文件会在编译时放在target里,如果是配置bean的xml文件,还需要使用@importResource (例如@ImportResource(locations = “classpath:configure.xml”)) configure.xml放在src/main/resources/里面,在project structure里面设置的。