1.initMethod和destoryMethod
在註冊bean對象時可以通過initMethod和destoryMethod屬性指定該對象的初始化和銷燬方法,這些方法爲對應類中的普通方法。
@Bean(initMethod = "init",destroyMethod = "destory")
public Person person(){
return new Person();
}
當添加@Scope(“prototype”)註解時不會調用指定的銷燬方法。
2.InitializingBean,DisposableBean接口
實現InitializingBean,DisposableBean接口,在容器初始化bean對象時會調用afterPropertiesSet方法,容器銷燬時會調用destroy方法。
public void destroy() throws Exception {
System.out.println("Cat destory...");
}
public void afterPropertiesSet() throws Exception {
System.out.println("Cat init...");
}
3.@PostConstruct和@PreDestroy
在對應的方法上添加@PostConstruct後在容器創建bean對象後便會調用該方法,當容器銷燬前會調用被@PreDestroy標記的方法。
@PostConstruct
public void init(){
System.out.println("Dog init...");
}
@PreDestroy
public void destory(){
System.out.println("Dog destory...");
}
4.BeanPostProcessor
實現BeanPostProcessor並重寫postProcessBeforeInitialization和postProcessAfterInitialization方法後,容器會在每次創建bean對象時調用postProcessBeforeInitialization方法,當對象創建並初始化完成後會調用postProcessAfterInitialization方法。
public class Color implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("before"+beanName);
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("after"+beanName);
return bean;
}
}
5.@Value
使用此註解可以給對應的屬性直接賦值,可以是字符串或其他類型,同時也支持spEL。
@Value("zhangshan")
private String name;
也可以讀取配置文件中的值
@Value("${book.price}")
private String price;
6.@PropertySource
使用此註解可以導入任意多份的配置文件。
@Configuration
@PropertySource({"classpath:/config.properties"})
@ComponentScan(basePackages = {"com.xxx"})
public class MainConfig {
}
7.@AutoWire、@Qualifier、@Resource
這三個註解都是用來將spring容器中的對象按照名稱或id注入到對應的屬性上,也可以標記在方法上使用參數注入。
@Repository
public class BookDao {
//@Resource
//@Qualifier
@Autowired
private BookService bookService;
}