Spring 注解编程 Bean 配置
@Configuration
@Configuration 配置类
1 |
|
测试类
1 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; |
@Bean
xml 配置
1 |
|
java config
1 |
|
@Import
@Import 导入bean
1 |
|
org.springframework.context.annotation.ImportSelector 选择导入
1 |
|
org.springframework.context.annotation.ImportBeanDefinitionRegistrar 注册Bean
1 | class UserRegistrar implements ImportBeanDefinitionRegistrar { |
spring 注解编程中 @Enable**
组件,大量使用此种方式注册Bean。例:@EnableAspectJAutoProxy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 (ElementType.TYPE)
(RetentionPolicy.RUNTIME)
// 此处导入 (AspectJAutoProxyRegistrar.class)
public EnableAspectJAutoProxy {
/**
* Indicate whether subclass-based (CGLIB) proxies are to be created as opposed
* to standard Java interface-based proxies. The default is {@code false}.
*/
boolean proxyTargetClass() default false;
/**
* Indicate that the proxy should be exposed by the AOP framework as a {@code ThreadLocal}
* for retrieval via the {@link org.springframework.aop.framework.AopContext} class.
* Off by default, i.e. no guarantees that {@code AopContext} access will work.
* @since 4.3.1
*/
boolean exposeProxy() default false;
}
@ComponentScan
@ComponentScan 指定扫描的包目录
1 |
|
1 |
|
@Profile
1 |
|
在实际开发中,经常有开发,测试,生产环境的不同配置,使用 @Profile
可以有效解决。 命令行启动设置激活的 Profile java -Dspring.profiles.actives=dev app.jar
。
initMethod destroyMethod Bean 生命周期
基于 @Bean 配置1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class User {
public void initMethod() {
System.out.println("user initMethod");
}
public void destroyMethod() {
System.out.println("user destroyMethod");
}
}
public class MainConfig {
"initMethod", destroyMethod="destroyMethod") (initMethod=
public User devUser() {
return new User();
}
}
继承 org.springframework.beans.factory.InitializingBean 和 org.springframework.beans.factory.DisposableBean1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class User implements InitializingBean, DisposableBean {
public void afterPropertiesSet() throws Exception {
System.out.println("user initMethod");
}
public destroy() throws Exception {
System.out.println("user destroyMethod");
}
}
public class MainConfig {
public User devUser() {
return new User();
}
}
使用 javax.annotation.PostConstruct 和 javax.annotation.PreDestroy。 注意这两个注解是Java规范并不是spring内置的,
1 | public class User { |
@Scope
scope 取值:通常使用 singleton
, prototype
。 web环境有 request
, session
。 batch 环境 step
。1
2
3
4
5"initMethod", destroyMethod="destroyMethod") (initMethod=
"prototype") (
public User devUser() {
return new User();
}
默认是singleton
的,这里比较一下prototype
有什么不同:
- 每次在容器中获取的 User 都会调用 devUser() 方法获取 User 实例。
- 关闭容器不会调用 destroyMethod() 方法。
org.springframework.beans.factory.config.BeanPostProcessor Bean 实例化前置处理器
1 | public interface BeanPostProcessor { |
实现此接口会在spring容器初始化bean时调用