SpringBoot配置----@PropertySource、@ImportResource、@Bean

一、@PropertySource

如果想使用项目加载特定的配置文件,可以使用@PropertySource

新建一个项目

 DemoApplication.java

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.zk.demo;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
public class DemoApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
 
}

 Person.java

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.zk.demo;
 
import org.hibernate.validator.constraints.Email;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
 
import java.util.List;
 
@Component
//@Validated
@ConfigurationProperties(prefix = "person")
@PropertySource(value = "classpath:person.properties")
public class Person {
    //@Value("${person.last-name}")
    //@Email
    private String lastName;
    private String Sno;
    private int grade;
    private List<Object> list;
    public String getLastName() {
        return lastName;
    }
 
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
 
    public String getSno() {
        return Sno;
    }
 
    public void setSno(String sno) {
        Sno = sno;
    }
 
    public int getGrade() {
        return grade;
    }
 
    public void setGrade(int grade) {
        this.grade = grade;
    }
 
    public List<Object> getList() {
        return list;
    }
 
    public void setList(List<Object> list) {
        this.list = list;
    }
 
    @Override
    public String toString() {
        return "Person{" +
                "lastName='" + lastName + '\'' +
                ", Sno='" + Sno + '\'' +
                ", grade=" + grade +
                ", list=" + list +
                '}';
    }
}

 ZkController.java

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.zk.demo;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
 
import java.util.HashMap;
import java.util.Map;
 
@RestController
public class ZkController {
    @Autowired
    private Environment environment;
 
    @Value("${server.port}")
    private Integer port;
    @Value("${alipay.pay.appid}")
    private String appid;
    @Value("${alipay.pay.notify}")
    private String notify;
    @Value("${java.version}")
    private String javaVersion;
    @Value("${JAVA_HOME}")
    private String javaHome;
    @Value("${MAVEN_HOME}")
    private String mavenHome;
    @Value("#{11*2}")
    private Integer number;
 
    @GetMapping("/read/file")
    public Map<String, Object> readInfo1() {
        Map<String, Object> map = new HashMap<>();
        map.put("port", environment.getProperty("server.port"));
        map.put("appid", environment.getProperty("alipay.pay.appid"));
        map.put("notify", environment.getProperty("alipay.pay.notify"));
        map.put("javaversion", environment.getProperty("java.version"));
        map.put("javahome", environment.getProperty("JAVA_HOME"));
        map.put("mavenhome", environment.getProperty("MAVEN_HOME"));
        map.put("number",environment.getProperty("number"));
        return map;
    }
 
    @GetMapping("/read/value")
    public Map<String, Object> readInfo2() {
        Map<String, Object> map = new HashMap<>();
        map.put("port", port);
        map.put("appid", appid);
        map.put("notify", notify);
        map.put("javaversion", javaVersion);
        map.put("javahome", javaHome);
        map.put("mavenhome", mavenHome);
        map.put("number",number);
        return map;
    }
 
    @GetMapping("/read/v2")
    public Map<String, Object> r2() {
        Map<String, Object> map = new HashMap<>();
        map.put("port", port);
        map.put("appid", appid);
        map.put("notify", notify);
        map.put("javaversion", javaVersion);
        map.put("javahome", javaHome);
        map.put("mavenhome", mavenHome);
        map.put("number",number);
        return map;
    }
}

 application.properties

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 应用名称
spring.application.name=demo
# 应用服务 WEB 访问端口
server.port=8080
spring.main.banner-mode=console
alipay.pay.appid=123456
alipay.pay.notify=http://www.xxx.com
# person.grade=0
# person.list=a,b,c
# person.last-name=张坤
# person.sno=1223
number=11
 
server.servlet.encoding.charset=utf-8
server.servlet.encoding.force=true
server.servlet.encoding.enabled=true

 person.properties

1
2
3
4
person.grade=0
person.list=a,b,c
person.last-name=张坤
person.sno=1223
SpringBootApplicationTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.zk.demo;
 
import com.zk.demo.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
 
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootApplicationTest {
 
    @Autowired
    Person person;
    @Test
    public void ContextLoads(){
        System.out.println(person);
    }
}

 运行结果如下:

 使用@PropertySource可以读出特定配置文件中的数据

二、@ImportResource

@ImportResource的作用是导入Spring配置文件,让配置文件中的内容生效

SpringBoot里面没有Spring的配置文件,我们自己编写的配置文件也不能自动识别。

首先创建一个helloService

helloService.java

1
2
3
4
package com.zk.demo;
 
public class helloService {
}

beans.xml

在beans.xml中注入这个类

1
2
3
4
5
6
<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">
    <bean id="helloService" class="com.zk.demo.helloService"></bean>
</beans>

 在SpringBootApplicationTest.java中编写测试用例

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
package com.zk.demo;
 
import com.zk.demo.Person;
import org.springframework.context.ApplicationContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
 
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootApplicationTest {
 
    @Autowired
    Person person;
 
    @Autowired
    ApplicationContext ioc;
 
    @Test
    public void testHelloService(){
        Boolean result=ioc.containsBean("helloService");
        System.out.println(result);
    }
    @Test
    public void ContextLoads(){
        System.out.println(person);
    }
}

 运行测试用例

 此时运行结果为false。

说明IOC此时没有引入beans.xml这个配置文件,识别不到HelloService

然后在DemoApplication.java中使用@ImportResource注解引入beans.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.zk.demo;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
 
@ImportResource(locations = "classpath:beans.xml")
@SpringBootApplication
public class DemoApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
 
}

 此时获取值为true

三、@Bean

@Bean的作用是给容器中添加组件

 新建一个MyAppConfig.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.zk.demo;
 
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
/*
@Configuration:指明当前类是一个配置类:就是来替代之前的Spring的配置文件
在配置文件中用<bean></bean>标签添加组件
 */
@Configuration
public class MyAppConfig {
 
    @Bean
    public helloService helloService(){
        return new helloService();
    }
}

 DemoApplication.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.zk.demo;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
 
//@ImportResource(locations = "classpath:beans.xml")
@SpringBootApplication
public class DemoApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
 
}

 helloService.java

1
2
3
4
package com.zk.demo;
 
public class helloService {
}
SpringBootApplicationTest.java
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
package com.zk.demo;
 
import com.zk.demo.Person;
import org.springframework.context.ApplicationContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
 
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootApplicationTest {
 
    @Autowired
    Person person;
 
    @Autowired
    ApplicationContext ioc;
 
    @Test
    public void testHelloService(){
        Boolean result=ioc.containsBean("helloService");
        System.out.println(result);
    }
    @Test
    public void ContextLoads(){
        System.out.println(person);
    }
}

运行SpringBootApplicationTest.java中的testHelloService

当把@Bean注释掉之后

MyAppConfig.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.zk.demo;
 
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
/*
@Configuration:指明当前类是一个配置类:就是来替代之前的Spring的配置文件
在配置文件中用<bean></bean>标签添加组件
 */
@Configuration
public class MyAppConfig {
 
    //@Bean
    public helloService helloService(){
        return new helloService();
    }
}

当把@Bean注释掉之后,运行测试用例

posted @   leagueandlegends  阅读(67)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示