1.InitializingBean和DisposableBean
InitializingBean接口提供了afterPropertiesSet方法,用于在bean的属性设置好之后调用;
DisposableBean接口提供了destroy方法,用于在bean销毁之后调用;
public class TestComponent implements InitializingBean, DisposableBean {@Overridepublic void destroy() throws Exception {// 清理代码System.out.println("Bean is destroyed");}@Overridepublic void afterPropertiesSet() throws Exception {// 初始化代码System.out.println("Bean is initialized");}
}
2.PostConstruct和PreDestroy
PostConstruct用于依赖注入完成之后执行初始化方法;
PreDestroy用于在Bean销毁之前执行清理方法
@PostConstructpublic void init(){System.out.println("Bean is init");}@PreDestroypublic void clean(){System.out.println("PreDestroy!");}
3.Bean 定义的 initMethod 和 destroyMethod
通过@Bean注解的两个属性,指定在Bean初始化和销毁的时候执行指定的方法;
@Configuration
public class TestConfig {@Bean(initMethod = "init", destroyMethod = "cleanup")public MyBean myBean() {return new MyBean();}public static class MyBean {public void init() {System.out.println("myBean init");}public void cleanup() {System.out.println("myBean cleanup");}}
}
4.BeanPostProcessor接口
用于在bean初始化之前和初始化之后进行某种操作;主要有两个接口
postProcessBeforeInitialization:bean初始化之前执行某种操作
postProcessAfterInitialization:bean初始化之后执行某种操作
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {@Overridepublic Object postProcessBeforeInitialization(Object bean, String beanName) {System.out.println("postProcessBeforeInitialization:"+beanName);return bean;}@Overridepublic Object postProcessAfterInitialization(Object bean, String beanName) {System.out.println("postProcessAfterInitialization:"+beanName);return bean;}
}
注意:系统中的所有bean初始化都会调这两个方法;慎重使用
5.ApplicationContextAware和BeanNameAware
ApplicationContextAware提供setApplicationContext,可以获取spring的上下文 BeanNameAware提供setBeanName,可以获取当前bean的名称;
@Component
public class MyAwareBean implements ApplicationContextAware, BeanNameAware {private String beanName;private static ApplicationContext mApplicationContext;@Overridepublic void setBeanName(String name) {this.beanName = name;// 记录 Bean 名称log.info("Bean name set to {}", name);}@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {mApplicationContext = applicationContext;}
}
6.FactoryBean
接口定义如下
public interface FactoryBean<T> {String OBJECT_TYPE_ATTRIBUTE = "factoryBeanObjectType";@NullableT getObject() throws Exception;@NullableClass<?> getObjectType();default boolean isSingleton() {return true;}
}
作用是生成其他bean,示例:
@Component
public class MyFactoryBean implements FactoryBean<MyFactoryBean.MyCustomBean> {@Overridepublic MyCustomBean getObject() throws Exception {return new MyCustomBean();}@Overridepublic Class<?> getObjectType() {return MyCustomBean.class;}public class MyCustomBean {// 自定义 Bean 的逻辑private String a1 = "test";public String getA1() {return a1;}}
}
7.EnvironmentAware, ResourceLoaderAware
EnvironmentAware提供了setEnvironment,实现了对Environment的操作;
ResourceLoaderAware提供了setResourceLoader,实现了对资源的操作;
@Component
public class MyEnvironmentAwareBean implements EnvironmentAware, ResourceLoaderAware {private Environment environment;private ResourceLoader resourceLoader;@Overridepublic void setEnvironment(Environment environment) {this.environment = environment;}@Overridepublic void setResourceLoader(ResourceLoader resourceLoader) {this.resourceLoader = resourceLoader;}
}
8.BeanFactoryAware
可以获取到BeanFactory,然后操作spring中的bean
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.stereotype.Component;@Component
public class MyBeanFactoryAware implements BeanFactoryAware {private BeanFactory beanFactory;@Overridepublic void setBeanFactory(BeanFactory beanFactory) {this.beanFactory = beanFactory;}
}
9.profile
设置在某个环境时激活某个bean
@Configuration
public class MyConfiguration {@Bean@Profile("dev")public MyBean devMyBean() {System.out.println("MyBean dev");return new MyBean();}@Bean@Profile("prod")public MyBean prodMyBean() {System.out.println("MyBean prod");return new MyBean();}public static class MyBean {// Bean 实现}
}
10.@Lazy、@DependsOn、@Order、@Conditional
Lazy用于延迟加载,当bean被注入的时候才进行加载;
DependsOn声明bean之间的依赖顺序,一个bean的加载依赖另外一个bean,确保一个bean先初始化之后,再加载另外一个bean;通常用来管理bean之间初始化顺序和依赖管理;
order用于bean初始化的顺序;
Conditional基于特定的条件才会创建bean;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;@Configuration
public class MyConfiguration {@Bean@Conditional({MyCondition.class})public MyBean myConditionalBean() {return new MyBean();}public static class MyBean {// Bean 实现}public static class MyCondition implements Condition {@Overridepublic boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {Environment env = context.getEnvironment();// 定义条件逻辑return env.containsProperty("my.custom.condition");}}
}