第二章 Spring常用配置

2017-06-30  本文已影响0人  TheMrBigHead

第二章 Spring常用配置

2.1 Bean的Scope

@Scope注解
(1) singleton:一个Spring容器中只有一个Bean实例,<b>此为Spring的默认配置,全容器共享一个实例</b>
(2) prototype : 每次调用都会新建一个Bean的实例。
(3) request : Web项目中,每个http request都会新建一个Bean的实例。
(4) session : Web项目中,每个http session都会新建一个Bean的实例。
(5) golobalSession : 这个只在portal应用中有用,给每个global http session新建一个Bean的实例。

  @Service
  @Scope("prototype")
  public class DemoPrototypeService {
  
  } 
2.2 Spring EL和资源调用

Spring EL-Spring表达式语言,支持在xml和注解中使用表达式。

使用@Value注入。

  // 注入普通字符串
  @Value("普通字符串")
  private String normalString;
  <dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.3</version>
  </dependency>

  @Configuration
  @PropertySource("classpath : test.properties")
  public class ELConfig {
    // 注入普通字符串
    @Value("I Love U !")
    private String normal;

    // 注入操作系统属性
    @Value(#{systemProperties['os.name']})
    private String osName;

    // 注入表达式结果
    @Value("#{ T(java.lang.Math).random() * 100.0}")
    private double randomNumber;

    // 注入其他Bean属性
    @Value("#{demoService.another}")
    private String fromAnother;

    // 注入文件资源
    @Value("classpath : test.txt")
    private Resource testFile;

    // 注入网址资源
    @Value("http://www.baidu.com")
    private Resourct testUrl;

    // 注入配置文件
    @Value("${book.name}")
    private String bookName;

    @Autowired
    private Environment environment;

    @Bean
    public static PropertySourcesPlaceholerConfigurer propertyConfig() {
      return new PropertySourcesPlaceholerConfigurer();
    }
    ...
  }
2.3 Bean的初始化和销毁

Spring对Bean的生命周期的操作提供了支持。

(1) Java配置方式: 使用@Bean的initMethod和destroyMethod(相当于xml配置的init-method和destroy-method)。

  @Bean(initMethod="init", destroyMethod="destroy") // init和destroy是两个方法的名字

(2)注解方式: 利用JSR-250的@PostConstruct和@PreDestory。

  <dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>jsr250-api</artifactId>
    <version>1.0</version>
  </dependency>

  public class JSR250WayService {
    @PostConstruct
    public void init() {
    }

    public JSR250WayService () {
    
    }
    
    @PreDestory
    public void destroy() {
    }
  }
2.4 Profile

<p>Profile为在不同环境下使用不同的配置提供了支持。</p>

  1. 通过设定Environment的ActiveProfiles来设定当前context需要使用的配置环境。在开发中使用@Profile注解类或者方法,达到在不同情况下选在实例化不同的Bean。

  2. 通过jvm的spring.profiles.active参数来设置配置环境。

  3. Web项目设置在Servlet的context parameter中。

2.5 事件

<p>详情见书</p>

上一篇 下一篇

猜你喜欢

热点阅读