1.InitializingBean
接口类,主要用于初始化处理。继承该类并实现afterPropertiesSet()方法。
class test implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception{
//方法内容
}
}
在spring启动的时,创建对象后会调用该方法进行处理。
当需要在项目启动时进行一些初始化动作时,使用此类,但是会将代码耦合进spring中,因此不推荐使用。可以使用@PostConstruct注解或者为POJO类指定其初始化方法来完成初始化。
2.@Bean
//@Configuration标注在类上,相当于把该类作为spring的xml配置文件中的<beans>,作用为:配置spring容器(应用上下文)
@Configuration
public class BeanTest {
@Bean(name = "bean", initMethod = "init")
public BeanTest beanTest() {
return new BeanTest();
}
public void init(){
System.out.println("这是一个bean的初始化方法");
}
}
3.@PostConstruct
@Component
public class BeanTest {
@PostConstruct
public void init(){
System.out.println("这是一个bean的初始化方法");
}
@PreDestroy
public void destory() {
System.out.println("这是一个bean的销毁方法");
}
}