Fork me on GitHub

Spring Boot 核心注解解析

[TOC]

Spring Boot方式的项目已经逐步成为Java应用开发领域的主流框架,开发者不仅可以创建生产级的Spring应用,还能轻松通过一些注解配置与目前比较火热的微服务框架SpringCloud集成。Spring Boot极大地简化了项目的配置,最大化地实现了“约定大于配置”的原则,然后虽然开发方便了,但也很容易让人云里雾里,特别是各种注解很容易让人“知其然而不知其所以然”,因此,要想用好Spring Boot就必须对其提供的各类功能注解有一个全面而清晰地认识和理解。因此特意去各大博客摘录了一些常用注解的解释,大家一起学习吧。。。

1. @Configuration

从Spring3.0,@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。

注意:@Configuration注解的配置类有如下要求:

@Configuration不可以是final类型;
@Configuration不可以是匿名类;
嵌套的configuration必须是静态类。

一、用@Configuration加载spring

1.1、@Configuration配置spring并启动spring容器

@Configuration标注在类上,相当于把该类作为spring的xml配置文件中的,作用为:配置spring容器(应用上下文)

1
2
3
4
5
6
7
8
9
10
package com.dxz.demo.configuration;

import org.springframework.context.annotation.Configuration;

@Configuration
public class TestConfiguration {
public TestConfiguration() {
System.out.println("TestConfiguration容器启动初始化。。。");
}
}

相当于:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd" default-lazy-init="false">


</beans>

主方法进行测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.dxz.demo.configuration;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestMain {
public static void main(String[] args) {

// @Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext
ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);

// 如果加载spring-context.xml文件:
// ApplicationContext context = new
// ClassPathXmlApplicationContext("spring-context.xml");
}
}

从运行主方法结果可以看出,spring容器已经启动了:
1

1.2、@Configuration启动容器+@Bean注册Bean

@Bean标注在方法上(返回某个实例的方法),等价于spring的xml配置文件中的,作用为:注册bean对象

bean类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.dxz.demo.configuration;

public class TestBean {

private String username;
private String url;
private String password;

public void sayHello() {
System.out.println("TestBean sayHello...");
}

public String toString() {
return "username:" + this.username + ",url:" + this.url + ",password:" + this.password;
}

public void start() {
System.out.println("TestBean 初始化。。。");
}

public void cleanUp() {
System.out.println("TestBean 销毁。。。");
}
}

配置类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.dxz.demo.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
public class TestConfiguration {
public TestConfiguration() {
System.out.println("TestConfiguration容器启动初始化。。。");
}

// @Bean注解注册bean,同时可以指定初始化和销毁方法
// @Bean(name="testBean",initMethod="start",destroyMethod="cleanUp")
@Bean
@Scope("prototype")
public TestBean testBean() {
return new TestBean();
}
}

主方法测试类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.dxz.demo.configuration;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestMain {
public static void main(String[] args) {

// @Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext
ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);

// 如果加载spring-context.xml文件:
// ApplicationContext context = new
// ClassPathXmlApplicationContext("spring-context.xml");

//获取bean
TestBean tb = (TestBean) context.getBean("testBean");
tb.sayHello();
}
}

结果:
2

注:
(1)、@Bean注解在返回实例的方法上,如果未通过@Bean指定bean的名称,则默认与标注的方法名相同;
(2)、@Bean注解默认作用域为单例singleton作用域,可通过@Scope(“prototype”)设置为原型作用域;
(3)、既然@Bean的作用是注册bean对象,那么完全可以使用@Component、@Controller、@Service、@Ripository等注解注册bean,当然需要配置@ComponentScan注解进行自动扫描。

@Bean下管理bean的生命周期

可以使用基于 Java 的配置来管理 bean 的生命周期。@Bean 支持两种属性,即 initMethod 和destroyMethod,这些属性可用于定义生命周期方法。在实例化 bean 或即将销毁它时,容器便可调用生命周期方法。生命周期方法也称为回调方法,因为它将由容器调用。使用 @Bean 注释注册的 bean 也支持 JSR-250 规定的标准 @PostConstruct 和 @PreDestroy 注释。如果您正在使用 XML 方法来定义 bean,那么就应该使用 bean 元素来定义生命周期回调方法。以下代码显示了在 XML 配置中通常使用 bean 元素定义回调的方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Configuration
@ComponentScan(basePackages = "com.dxz.demo.configuration")
public class TestConfiguration {
public TestConfiguration() {
System.out.println("TestConfiguration容器启动初始化。。。");
}

//@Bean注解注册bean,同时可以指定初始化和销毁方法
@Bean(name="testBean",initMethod="start",destroyMethod="cleanUp")
@Scope("prototype")
public TestBean testBean() {
return new TestBean();
}
}

启动类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class TestMain {
public static void main(String[] args) {

ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);

TestBean tb = (TestBean) context.getBean("testBean");
tb.sayHello();
System.out.println(tb);

TestBean tb2 = (TestBean) context.getBean("testBean");
tb2.sayHello();
System.out.println(tb2);
}
}

结果:
3

分析:

结果中的1:表明initMethod生效

结果中的2:表明@Scope(“prototype”)生效

1.3、@Configuration启动容器+@Component注册Bean

bean类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.dxz.demo.configuration;

import org.springframework.stereotype.Component;

//添加注册bean的注解
@Component
public class TestBean {

private String username;
private String url;
private String password;

public void sayHello() {
System.out.println("TestBean sayHello...");
}

public String toString() {
return "username:" + this.username + ",url:" + this.url + ",password:" + this.password;
}

public void start() {
System.out.println("TestBean 初始化。。。");
}

public void cleanUp() {
System.out.println("TestBean 销毁。。。");
}
}

配置类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.dxz.demo.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
//添加自动扫描注解,basePackages为TestBean包路径
@ComponentScan(basePackages = "com.dxz.demo.configuration")
public class TestConfiguration {
public TestConfiguration() {
System.out.println("TestConfiguration容器启动初始化。。。");
}

/*// @Bean注解注册bean,同时可以指定初始化和销毁方法
// @Bean(name="testNean",initMethod="start",destroyMethod="cleanUp")
@Bean
@Scope("prototype")
public TestBean testBean() {
return new TestBean();
}*/
}

主方法测试获取bean对象:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.dxz.demo.configuration;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestMain {
public static void main(String[] args) {

// @Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext
ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);

// 如果加载spring-context.xml文件:
// ApplicationContext context = new
// ClassPathXmlApplicationContext("spring-context.xml");

//获取bean
TestBean tb = (TestBean) context.getBean("testBean");
tb.sayHello();
}
}

sayHello()方法都被正常调用。
4

1.4、使用 AnnotationConfigApplicationContext 注册 AppContext 类的两种方法

1.4.1、 配置类的注册方式是将其传递给 AnnotationConfigApplicationContext 构造函数

1
2
3
4
5
6
7
8
9
public static void main(String[] args) {

// @Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext
ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);

//获取bean
TestBean tb = (TestBean) context.getBean("testBean");
tb.sayHello();
}

1.4.2、 AnnotationConfigApplicationContext 的register 方法传入配置类来注册配置类

1
2
3
4
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AppContext.class)
}

1.5、配置Web应用程序(web.xml中配置AnnotationConfigApplicationContext)

过去,您通常要利用 XmlWebApplicationContext 上下文来配置 Spring Web 应用程序,即在 Web 部署描述符文件 web.xml 中指定外部 XML 上下文文件的路径。XMLWebApplicationContext 是 Web 应用程序使用的默认上下文类。以下代码描述了 web.xml 中指向将由 ContextLoaderListener 监听器类载入的外部 XML 上下文文件的元素。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>sampleServlet</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
</servlet>

...
</web-app>

现在,您要将 web.xml 中的上述代码更改为使用 AnnotationConfigApplicationContext 类。切记,XmlWebApplicationContext 是 Spring 为 Web 应用程序使用的默认上下文实现,因此您永远不必在您的web.xml 文件中显式指定这个上下文类。现在,您将使用基于 Java 的配置,因此在配置 Web 应用程序时,需要在web.xml 文件中指定 AnnotationConfigApplicationContext 类。上述代码将修改如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<web-app>
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.
support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
demo.AppContext
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>sampleServlet</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.
support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
</servlet>

...
</web-app>

以上修改后的 web.xml 现在定义了 AnnotationConfigWebApplicationContext 上下文类,并将其作为上下文参数和 servlet 元素的一部分。上下文配置位置现在指向 AppContext 配置类。这非常简单。下一节将演示 bean 的生命周期回调和范围的实现。

1.6、@Configuation总结

@Configuation等价于
@Bean等价于
@ComponentScan等价于<context:component-scan base-package=”com.dxz.demo”/>

二、组合多个配置类

2.1、在@Configuration中引入spring的xml配置

1
2
3
4
5
6
7
8
9
package com.dxz.demo.configuration2;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

@Configuration
@ImportResource("classpath:applicationContext-configuration.xml")
public class WebConfig {
}

bean类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.dxz.demo.configuration2;

public class TestBean2 {
private String username;
private String url;
private String password;

public void sayHello() {
System.out.println("TestBean2 sayHello...");
}

public String toString() {
return "TestBean2 username:" + this.username + ",url:" + this.url + ",password:" + this.password;
}

public void start() {
System.out.println("TestBean2 初始化。。。");
}

public void cleanUp() {
System.out.println("TestBean2 销毁。。。");
}
}

测试类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

package com.dxz.demo.configuration2;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestMain2 {
public static void main(String[] args) {

// @Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext
ApplicationContext context = new AnnotationConfigApplicationContext(WebConfig.class);

// 如果加载spring-context.xml文件:
// ApplicationContext context = new
// ClassPathXmlApplicationContext("spring-context.xml");

// 获取bean
TestBean2 tb = (TestBean2) context.getBean("testBean2");
tb.sayHello();
}
}

结果:
6

2.2、在@Configuration中引入其它注解配置

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.dxz.demo.configuration2;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;

import com.dxz.demo.configuration.TestConfiguration;

@Configuration
@ImportResource("classpath:applicationContext-configuration.xml")
@Import(TestConfiguration.class)
public class WebConfig {
}

测试类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.dxz.demo.configuration2;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.dxz.demo.configuration.TestBean;

public class TestMain2 {
public static void main(String[] args) {

// @Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext
ApplicationContext context = new AnnotationConfigApplicationContext(WebConfig.class);

// 如果加载spring-context.xml文件:
// ApplicationContext context = new
// ClassPathXmlApplicationContext("spring-context.xml");

// 获取bean
TestBean2 tb2 = (TestBean2) context.getBean("testBean2");
tb2.sayHello();

TestBean tb = (TestBean) context.getBean("testBean");
tb.sayHello();
}
}

结果:
7

2.3、@Configuration嵌套(嵌套的Configuration必须是静态类)

通过配置类嵌套的配置类,达到组合多个配置类的目的。但注意内部类必须是静态类。
上代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.dxz.demo.configuration3;

import org.springframework.stereotype.Component;

@Component
public class TestBean {

private String username;
private String url;
private String password;

public void sayHello() {
System.out.println("TestBean sayHello...");
}

public String toString() {
return "username:" + this.username + ",url:" + this.url + ",password:" + this.password;
}

public void start() {
System.out.println("TestBean start");
}

public void cleanUp() {
System.out.println("TestBean destory");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.dxz.demo.configuration3;

public class DataSource {

private String dbUser;
private String dbPass;
public String getDbUser() {
return dbUser;
}
public void setDbUser(String dbUser) {
this.dbUser = dbUser;
}
public String getDbPass() {
return dbPass;
}
public void setDbPass(String dbPass) {
this.dbPass = dbPass;
}
@Override
public String toString() {
return "DataSource [dbUser=" + dbUser + ", dbPass=" + dbPass + "]";
}
}

配置类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.dxz.demo.configuration3;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.dxz.demo.configuration3")
public class TestConfiguration {
public TestConfiguration() {
System.out.println("TestConfiguration容器启动初始化。。。");
}

@Configuration
static class DatabaseConfig {
@Bean
DataSource dataSource() {
return new DataSource();
}
}
}

启动类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.dxz.demo.configuration3;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestMain {
public static void main(String[] args) {

// @Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContexts
ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);

//bean
TestBean tb = (TestBean) context.getBean("testBean");
tb.sayHello();

DataSource ds = (DataSource) context.getBean("dataSource");
System.out.println(ds);
}
}

结果:

1
2
3
TestConfiguration容器启动初始化。。。
TestBean sayHello...
DataSource [dbUser=null, dbPass=null]

三、@EnableXXX注解

配合@Configuration使用,包括 @EnableAsync, @EnableScheduling, @EnableTransactionManagement, @EnableAspectJAutoProxy, @EnableWebMvc。

@EnableWebMvc

在springboot mvc或者java config配置中,如果我们项配置mvc相关的一些配置,那么就会涉及到这三个注解中的某个,那么他们之间有什么关系呢。

@EnableWebMvc = WebMvcConfigurationSupport,使用@EnableWebMvc注解就等于扩展了WebMvcConfigurationSupport,但是没有扩展任何方法。具体用法有如下三种:

@EnableWebMvc+extends WebMvcConfigurationAdapter,在扩展的类中重写父类的方法即可,这种方式会屏蔽springboot的@EnableAutoConfiguration中的设置。

extends WebMvcConfigurationSupport,在扩展的类中重写父类的方法即可,这种方式会屏蔽springboot的@EnableAutoConfiguration中的设置。

extends WebMvcConfigurationAdapter,在扩展的类中重写父类的方法即可,这种方式依旧使用springboot的@EnableAutoConfiguration中的设置。

前两种用法会屏蔽springboot的@EnableAutoConfiguration中的设置,最后一种用法则不会屏蔽默认设置,所以要使用部分spring mvc默认配置的话,就需要使用第三种配置方式。

@EnableScheduling、@Scheduled

1. 在 main 中开启定时任务的注解 @EnableScheduling

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.cun;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableScheduling //开启定时任务注解
@SpringBootApplication
public class AsMailTaskApplication {

public static void main(String[] args) {
SpringApplication.run(AsMailTaskApplication.class, args);
}
}

2.在 Service 中编写定时任务 @Scheduled

fixedDelay: 每次方法执行完毕后,等待Nms再执行此方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 每次方法执行完毕后,等待5s再执行此方法。
* 同时只能有个线程运行此方法
*/
@Scheduled(fixedDelay=5000)
public void fixedDelay() {
try {
// 执行方法需要10s
Thread.sleep(1000 * 10);
} catch (InterruptedException e) {
}
log.info("fixedDelay--");
}

注意:定时方法返回值只能是void且不能有传入参数

fixedRate: 每隔5s调用一次此方法,无论之前的方法是否执行完毕

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* 每隔5s调用一次此方法,无论之前的方法是否执行完毕
* 同时可能有N个线程执行此方法
*
*/
@Scheduled(fixedRate=5000)
public void fixedRate() {
try {
// 执行方法需要10s
Thread.sleep(1000 * 10);
} catch (InterruptedException e) {
}
log.info("fixedRate--");
}

initialDelay: 第一次调用此方法前的等待时间

1
2
3
4
5
6
7
8
/***
* initialDelay: 第一次调用此方法前的等待时间
*
*/
@Scheduled(initialDelay=1000, fixedRate=5000)
public void initialDelayAndfixedRate() {
log.info("initialDelayAndfixedRate--");
}

cron:通过cron配置值

1
2
3
4
5
6
7
8
9
10
/**
* 支持cron语法:
* 每个参数的意义分别是: second, minute, hour, day of month, month, day of week
*
* 如下:周一至周五,每隔5s执行一次方法
*/
@Scheduled(cron="*/5 * * * * SUN-MON")
public void cron() {
log.info("cron--");
}

3. Maven 依赖

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

四、@Profile逻辑组配置

@PropertySource注解可以配置读取单个或多个配置文件:
单个配置文件:

1
@PropertySource(value = "classpath:spring/config.properties")

多个配置文件:

1
@PropertySource(value = {"classpath:spring/config.properties","classpath:spring/news.properties"})

@PropertySource注解使用有两种方式:

1、@PropertySource + Environment,通过@PropertySource注解将properties配置文件中的值存储到Spring的 Environment中,Environment接口提供方法去读取配置文件中的值,参数是properties文件中定义的key值。

2、@PropertySource(PropertySourcesPlaceholderConfigurer)+@Value
示例1:@PropertySource + Environment

在spring3.1中(不是spring3.0)还可以这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.dxz.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

@Configuration
@ComponentScan(basePackages = "com.dxz.config")
@PropertySource(value = "classpath:spring/config.properties")
public class ServiceConfiguration {

@Autowired
Environment environment;

public ServiceConfiguration() {
System.out.println("ServiceConfiguration zheli");
}

//@Bean
public javax.sql.DataSource dataSource(){
String user = this.environment.getProperty("ds.user");
System.out.println(user);
return null;
}
}

配置文件config.properties:

1
2
3
4
5
key1=abc
key2=aaaaaaaaaaaaaaaaaaaa
key3=bbbbbbbbbbbbbbbbbbbbbbbbbbb
key4=cccccccccc
ds.user=admin

测试类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.dxz.config;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;


public class Test {
public static void main(String[] args) {

ApplicationContext context = new AnnotationConfigApplicationContext(ServiceConfiguration.class);

ServiceConfiguration hc2 = (ServiceConfiguration) context.getBean("serviceConfiguration");
hc2.dataSource();

}
}

结果:

1
2
3
root of context hierarchy
ServiceConfiguration zheli
admin

示例2: @PropertySource(PropertySourcesPlaceholderConfigurer)+@Value
创建Spring配置Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.dxz.config2;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@ComponentScan(basePackages = "com.dxz.config2")
public class AppConfigMongoDB {

@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.dxz.config2;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource(value = "classpath:spring/config.properties")
public class MongoDBConfig {
//1.2.3.4
@Value("${key1}")
private String mongodbUrl;

//hello
@Value("${ds.user}")
private String defaultDb;

@Override
public String toString() {
return "MongoDBConfig [mongodbUrl=" + mongodbUrl + ", defaultDb=" + defaultDb + "]";
}
}

测试类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.dxz.config2;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;


public class Test5 {

public static void main(String[] args) {

ApplicationContext context = new AnnotationConfigApplicationContext(AppConfigMongoDB.class);

MongoDBConfig ac = (MongoDBConfig)context.getBean("mongoDBConfig");
System.out.println(ac);

}
}

结果:

1
2
root of context hierarchy
MongoDBConfig [mongodbUrl=abc, defaultDb=admin]

spring4版本
在Spring 4版本中,Spring提供了一个新的注解——@PropertySources,从名字就可以猜测到它是为多配置文件而准备的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.dxz.config3;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.stereotype.Component;

@Component
@PropertySources({
@PropertySource("classpath:db.properties"),
//@PropertySource(value="classpath:db.properties", ignoreResourceNotFound=true),
@PropertySource("classpath:spring/config.properties")
})
public class AppConfig {
@Value("${key1}")
private String key1;

@Value("${key2}")
private String key2;

@Override
public String toString() {
return "AppConfig [key1=" + key1 + ", key2=" + key2 + "]";
}

}

spring的配置class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.dxz.config3;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@ComponentScan(basePackages = "com.dxz.config3")
public class AppConfiguation {

@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}

}

测试类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.dxz.config3;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;


public class Test6 {

public static void main(String[] args) {

ApplicationContext context = new AnnotationConfigApplicationContext(AppConfiguation.class);

AppConfig ac = (AppConfig)context.getBean("appConfig");
System.out.println(ac);

}

}

结果:
8

另外在Spring 4版本中,@PropertySource允许忽略不存在的配置文件。先看下面的代码片段:

1
2
3
4
5
@Configuration
@PropertySource("classpath:missing.properties")
public class AppConfig {
//something
}

如果missing.properties不存在或找不到,系统则会抛出异常FileNotFoundException。

Caused by: java.io.FileNotFoundException:
class path resource [missiong.properties] cannot be opened because it does not exist
幸好Spring 4为我们提供了ignoreResourceNotFound属性来忽略找不到的文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.dxz.config3;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.stereotype.Component;

@Component
@PropertySources({
//@PropertySource("classpath:db.properties"),
@PropertySource(value="classpath:db.properties", ignoreResourceNotFound=true),
@PropertySource("classpath:spring/config.properties")
})
public class AppConfig {
@Value("${key1}")
private String key1;

@Value("${key2}")
private String key2;

@Override
public String toString() {
return "AppConfig [key1=" + key1 + ", key2=" + key2 + "]";
}

}

最上面的AppConfiguation 的配置代码等于如下的XML配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

<context:component-scan base-package="com.9leg.java.spring"/>

<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<value>classpath:spring/config.properties</value>
</list>
</property>
</bean>
</beans>

五、使用外部变量

1、@PropertySource + Environment,通过@PropertySource注解将properties配置文件中的值存储到Spring的 Environment中,Environment接口提供方法去读取配置文件中的值,参数是properties文件中定义的key值。
2、@PropertySource(PropertySourcesPlaceholderConfigurer)+@Value

感谢您的赞赏,赚点辛苦奶粉钱