一、@Import注解
一般来说, 需要按模块或类别 分割Spring XML bean文件 成多个小文件, 使事情更容易维护和模块化。 例如
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<import resource="config/customer.xml"/>
<import resource="config/scheduler.xml"/>
</beans>
Spring3 JavaConfig它等效于 @Import 功能
package com.yiibai.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import({ CustomerConfig.class, SchedulerConfig.class })
public class AppConfig {
}
- @Import注解是引入带有@Configuration的java类;-------------这个注解帮助我们将多个配置文件(可能是按功能分,或是按业务分)导入到单个主配置中,以避免将所有配置写在一个配置中。
- 在spring在4.2,@Import注解支持导入普通的java类,并将其声明成一个bean;
package com.dxz.imports;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import(DemoService.class) // 在spring 4.2之前是不不支持的
public class DemoConfig {
}
package com.dxz.imports;
public class DemoService {
public void doSomething() {
System.out.println("everything is all fine");
}
}
package com.dxz.imports;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.dxz.imports");
DemoService ds = context.getBean(DemoService.class);
ds.doSomething();
}
}
二、@ImportResource注解
@ImportResource(value=“classpath:applicationContext1.xml”) <============>等同于xml配置:
<import resource="applicationContext1.xml" />
(1)value:为String数组,内容为一个或多个xml文件的路径(相对于classpath);
@ImportResource(value={“classpath:applicationContext1.xml,file:applicationContext2.xml”})
(2) locations:同value属性;
- @ImportResource,是引入spring配置文件.xml,实现xml配置的装载;
- @ImportResource:通过locations属性或者value属性,加载对应的xml配置文件,同时需要配合@Configuration注解一起使用,定义为配置类;
- @ImportResource引入的配置类必须在启动类中扫描到;
使用@ImportResource 和 @Value 注解进行资源文件读取
package com.dxz.imports4;
public class MyDriverManager {
public MyDriverManager(String url, String username, String password) {
System.out.println("url : " + url);
System.out.println("username : " + username);
System.out.println("password : " + password);
}
}
创建StoreConfig
package com.dxz.imports4;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration
@ImportResource("classpath:applicationContext-democonfig2.xml")
public class StoreConfig {
@Value("${url}")
private String url;
@Value("${username}")
private String username;
@Value("${password}")
private String password;
@Bean
public MyDriverManager myDriverManager() {
return new MyDriverManager(url, username, password);
}
}
XML配置(context:property-placeholder 指定资源文件的位置)applicationContext-democonfig2.xml
<?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.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<context:property-placeholder location="classpath:config4.properties" />
<context:component-scan base-package="com.dxz.imports4">
</context:component-scan>
</beans>
创建资源文件config4.properties
url=127.0.0.1 username=root password=123456
三、@PropertySource注解
- @PropertySource注解加载指定的属性文件;
- @PropertySource注解的属性value,是一个String数组,内容为一个或多个xml文件的路径(相对于classpath);
- @PropertySource注解内部的属性使用,配合@value注解;----properties属性文件是key-value格式的,@value("${key}");
单个配置文件:
@PropertySource(value = "classpath:spring/config.properties",ignoreResourceNotFound = true,encoding = "UTF-8")
多个配置文件:
@PropertySource(value = {"classpath:spring/config.properties","classpath:spring/news.properties"})
@PropertySource注解使用有两种方式:
1、@PropertySource + Environment,通过@PropertySource注解将properties配置文件中的值存储到Spring的 Environment中,Environment接口提供方法去读取配置文件中的值,参数是properties文件中定义的key值。
@Configuration
@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;
}
}
2、@PropertySource + @Value
@Component
@PropertySource("classpath:db.properties")
public class DBConnection {
@Value("${DB_DRIVER_CLASS}")
private String driverClass;
@Value("${DB_URL}")
private String dbUrl;
@Value("${DB_USERNAME}")
private String userName;
@Value("${DB_PASSWORD}")
private String password;
public DBConnection(){}
public void printDBConfigs(){
System.out.println("Db Driver Class = " + driverClass);
System.out.println("Db url = " + dbUrl);
System.out.println("Db username = " + userName);
System.out.println("Db password = " + password);
}
}
四、@Value注解
- @Value 为属性注入值(通常使用在属性上较多);
- 使用方式:
@Value("normal")
private String normal; // 注入普通字符串
@Value("#{systemProperties['os.name']}")
private String systemPropertiesName; // 注入操作系统属性
@Value("#{ T(java.lang.Math).random() * 100.0 }")
private double randomNumber; //注入表达式结果
@Value("#{beanInject.another}")
private String fromAnotherBean; // 注入其他Bean属性:注入beanInject对象的属性another,类具体定义见下面
@Value("classpath:com/hry/spring/configinject/config.txt")
private Resource resourceFile; // 注入文件资源
@Value("http://www.baidu.com")
private Resource testUrl; // 注入URL资源
五、@ConfigurationProperties注解
- @ConfigurationProperties可以使用在类上、方法上;
- 在类上使用:
(1)在application.properties 中加入如下配置:
com.example.demo.name=${aaa:hi}
com.example.demo.age=11
com.example.demo.address[0]=北京
com.example.demo.address[1]=上海
com.example.demo.address[2]=广州
com.example.demo.phone.number=1111111
(2) 加在类上,需要和@Component注解、@Configuration等,结合使用.代码如下:
@Component
@ConfigurationProperties(prefix = "com.example.demo")
@PropertySource(value="classpath:application.properties")
public class People {
private String name;
private Integer age;
private List<String> address;
private Phone phone;
}
说明:上述代码中,在People类中增加了ConfigurationProperties注解,并且指明了属性的前缀为com.example.demo。这样Springboot在处理的时候,会去扫描当前类中的所有字段并进行属性的查找以及组装。比如我们配置的prefix = "com.example.demo",People类中有一个name字段,则name字段需要匹配的属性是prefix+字段=com.example.demo.name。
然后,根据组装好的属性,去PropertySource引用的properties文件找对应的属性值,找到了之后,自动注入People类相应的属性中,例如将application.properties中key为com.example.demo.name的值,注入到People类的name属性;
3、在方法上使用:
(1)在application.properties 中的配置同上,不变:
(2)People类;
public class People {
private String name;
private Integer age;
private List<String> address;
private Phone phone;
// get set 忽略,自己加上即可..
}
(3) 通过@Bean的方式进行声明,这里我们加在启动类即可,代码如下:
@Configuration
@PropertySource(value="classpath:application.properties")
public class DemoApplication {
@Bean
@ConfigurationProperties(prefix = "com.example.demo")
public People people() {
return new People();
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}