spring注解
spring context
注册组件
xml方式
resources下:标签–> ClassPathXmlApplicationContext(“beans.xml”);
注解方式
@Configuration: 放在配置类上。配置类 @Bean: 获取对象的方法,默认id为方法名。可通过注解value指定id。
@ComponentScan:放在配置类上 (value=“top.fan4.dy”,excludeFilter按照不同方式排除,include)==>@ComponentScans。也可自定义过滤规则
@Scope:调整作用域 singleton 默认单例 IOC启动时即创建。饿汉模式 @Lazy 懒加载 prototype 多实例 获取时即重新创建 request(web) session(web)
@Condational 满足条件时注册bean。可放在类或者方法上 condationClass implements Condation。 @Condational(condationClass.class)
组件注册方式:
-
包扫描【@ComponentScan配置类上】 + 组件注解标注(标注了@Controller(controller层),@Service(serice层),@Repository(dao层),@Component)可被扫描加入容器
-
@Bean 【方法上】 (第三方组件,注册在方法上返回创建对应对象的类即可)
-
@Import 【配置类上】 (快速给容器导入组件) {Class.class}id为全类名。 ImportSelector: class MyImportSelector implements ImportSelector{全类名} @Import({MyImportSelector.class}) @ImportBeanDefination 手动注册
FactoryBean class MyBeanFactory implements FactoryBean{} @Bean public MyBeanFactory MyBeanFactory(){return new MyBeanFactory()} xxxx.getBean(“MyBeanFactory”) getBean("&MyBeanFactory") ==> 得到实际的bean|MyBeanFactory
生命周期
- @Bean() 设置初始化(init)方法和销毁(destory)方法。在创建对象完成和容器关闭时。多实例时不管理bean和销毁。
- bean implements InitializingBean,DisposableBean
- jsr250 @PostConstruct(方法上使用,对象创建和赋值之后调用) 和 @PreDestory(方法上使用,容器移除对象之前)
- BeanPostProcessor【interface】 BeanPostProcessor 包装返回obj 生命周期:初始化->对象创建完成->赋值->初始化方法->BeanPostProcessor->postProcessAfterInitialation
属性赋值
pre: 配置文件的导入:(导入外部文件到运行环境变量)
- xml:{context:property-placeholder location=“classpath:person.properties”}
- 注解:@PropertySource(value{“classpath:/person.properties”,“files:/etc/conf.properties”},encoding=“utf8”?) 使用位置:配置类上
@Value
- 普通值
- #{}:SpEL(spring表达式)。
- ${}:配置文件(环境变量中的值) 需要@PropertySource先导入
自动装配
利用spring依赖注入完成对IOC中各个组件的依赖关系赋值。
-
@Autowired(required) 属性从容器中寻找值注入。使用位置:构造器/构造函数上,方法(注入参数)上,参数位置,属性上 // 优先按照类型去容器中寻找,容器中存在多个按照属性的变量名注入。(Person p;Person p1;) // @Primary: 容器创建的方法上使用,注入时使用的默认容器 // @Qualifier:容器存在多个值时可通过此注解指定使用容器中的某个id容器。 // 优先级: @Qualifier > @Primary > 默认类型 @Bean标注的方法中的参数默认从容器中获取。
-
@Resource(name)和@Inject()[分别来自jsr250,jsr330] @Resource:默认按照属性变量名,可通过name属性指定 @Inject:需要导入javax.Inject,除不支持@Autowired的required属性外,其它相同。
-
XXAware
-
@Profile:根据环境激活组件功能。(开发环境/测试环境/生产环境。使用位置:配置类或者@Bean上
demo: @Profile(“dev”) / @Profile(“default”) @Bean profile激活:
1. 动态参数:-Dspring.profilesactivate=test
-
applicationContext.getEnvironment().setActivateProfiles("dev","test"); applicationContext.register(Configclass.class); applicationContext.refresh();
-
? resolver aware
- Author: DY
- Link: http://4fan.top/posts/spring%E6%B3%A8%E8%A7%A3/
- License: This work is under a 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议. Kindly fulfill the requirements of the aforementioned License when adapting or creating a derivative of this work.