目录
一、向容器中添加Bean的几种方式:
@Bean
@Bean
public DefaultHandler defaultHandler() {
return new DefaultHandler();
}
@CompoentScan
@Configuration
@ComponentScan("com.xxx.xxxx")
public class Configuration {
}
@Import
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Import {
/**
* {@link Configuration}, {@link ImportSelector}, {@link ImportBeanDefinitionRegistrar}
* or regular component classes to import.
*/
Class<?>[] value();
}
FactoryBean<T>
@Data
public class MarkerFactoryBean<T> implements FactoryBean<T> {
private T object;
@Override
public T getObject() {
return new MarkerProxy<T>(object).newProxyInstance();
}
@Override
public Class<?> getObjectType() {
return object.getClass();
}
@Override
public boolean isSingleton() {
return true;
}
}
二、指定bean的初始化和销毁方法
在Bean声明时显示指定
@Bean(initMethod = "init", destroyMethod = "destroy")
public DefaultHandler defaultHandler() {
return new DefaultHandler();
}
通过实现InitializingBean和DisposableBean接口
@Component
public class DefaultHandler implements InitializingBean, DisposableBean {
@Override
public void destroy() throws Exception {
}
@Override
public void afterPropertiesSet() throws Exception {
}
}
通过@PostConstruct和@PreDestroy注解
@Component
public class DefaultHandler {
@PostConstruct
public void postConstruct() {
}
@PreDestroy
public void preDestroy() {
}
}