资源信息都来自网络,本人只是记录作为个人笔记
一. Bean的Scope
Scope描述是spring容器如何创建Bean的实例。通过@Scope注解来实现。
- Singleton:一个spring容器中只有一个bean的实例,此为spring的默认配置,全容器共享一个实例。默认,相当于@Scope(“singleton”)
- Prototype:每次调用新建一个Bean的实例。eg:@Scope(“prototype”)
- Request :web项目中,给每一个http request新建一个bean实例
- Session:web项目中,给每一个http session新建一个bean实例
- GlobalSession:这个只在portal应用中有用,给每个global http session新建一个bean实例。
二. Spring EL和资源调用
Spring EL-Spring表达式语言,支持在xml和注解中使用表达式,类似与JSP的EL表达式语言。开发中经常涉及到调用各种资源的情况,包含文件,网址,配置文件,系统环境变量等,使用spring表达式语言实现资源注入。
spring中主要在注解@Value的参数中使用表达式。
- 注入普通字符。
@Value("hello world")
- 注入操作系统属性。
@Value("#{systemProperties['os.name']}")
- 注入表达式运算结果。
@Value("#{T(java.lang.Math).random()*100.0}")
- 注入其他bean的属性。
DemoService.another @Value("#{demoService.another}")
- 注入文件内容。
@Value("classpath:test.txt") IOUtils.toString(testFile.getInputStream())
- 注入网址内容
@Value("http://www.baidu.com") IOUtils.toString(testUrl.getInputStream())
- 注入属性文件。
test.properties book.name="spring boot" book.author="shm" @Value("${book.name}")
@Autowired private Environment environment; @Bean public static PropertySourcesPlaceholderConfigurer propertyConfigure(){ return new PropertySourcesPlaceholderConfigurer (); } -->environment.getProperty("book.author")
三. bean的初始化和销毁
spring对bean的生命周期的操作提供了支持。
- java配置方式:使用@Bean的initMehod和destroyMethod(相当于xml配置的init-method和destory-method)
@Bean(initMethod="init",destroyMethod="destroy")
- 注解方式:利用JSR-250的@PostConstruct和@PreDestroy。
依赖:
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency>
四. Profile
profile为在不同环境下使用不同的配置提供支持(开发配置和生产配置,如,数据库的配置)
- 通过设定Environment的ActiveProfiles来设定当前context需要使用的配置环境。在开发中使用@Profile注解或者方法,达到在不同情况下选择实例化不同的bean。
@Configuration public class ProfileConfig{ @Profile("dev") public DemoBean devDemoBean(){ return new DemoBean("from devlopment profile") } @Profile("prod") public DemoBean devDemoBean(){ return new DemoBean("from production profile") } } //应用 //将互动的profile设置为prod context.getEnvironment().setActiveProfiles("prod") //后置注册bean配置类 context.register(ProFileConfig.class); //刷新容器 contest.refresh();
- 通过设定jvm的spring.profiles.active参数来设置配置环境。
- web项目设置在Servlet的context.parameter中。
五.事件(Application Event)
spring的事件(Application Event)为Bean和Bean之间的消息通信提供了支持。
spring的时间需要遵循如下流程:
- 自定义事件,继承ApplicationEvent
DemoEvent extends ApplicationEvent
- 定义事件监听器,实现ApplicationListener
DemoListener implements ApplicationListener<DemoEvent>
- 使用容器发布事件
@Autowired ApplicationContext applicationContext; --> applicationContext.publishEvent(new DemoEvent(this,msg))