Spring Java Config——@PropertySource和@Value、自动装配等

目录

一、@PropertySource和@Value

跳转到目录

使用@Value赋值: @Value默认值的使用方法

  1. 基本数值
  2. SpEL, #{}; SpringEL表达式
  3. 可以写${}, 取出配置文件properties中的值(在运行环境变量里的值)
  • @PropertySource用来加载资源文件
  • @Value 用于注入基本类型String类型的数据

DataSource类

@Setter
@Getter
@ToString
@AllArgsConstructor
public class DataSource {

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

资源文件

db.username=zygui
db.password=1234
db.url=https://blog.csdn.net/m0_37989980

配置类

  • 该bean是为了解析@Value中SpringEL表达式
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}
@Configuration
@PropertySource("classpath:db.properties")
public class AppConfig {

    // @Value相当于 <property name="username" value="${db.username}"/>
    @Value("${db.username}")
    private String username;
    @Value("${db.password}")
    private String password;
    @Value("${db.url}")
    private String url;

    // 该bean是为了解析@Value中SpringEL表达式
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean
    public DataSource dataSource() {
        return new DataSource(username, password, url);
    }
}

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class)
public class AppTest {

    @Autowired
    private DataSource dataSource;

    @Test
    public void test(){
        System.out.println(dataSource);
    }
}

二、自动装配@Autowired, @Qualifier, @Resource, @RequiredArgsConstructor

跳转到目录

1、@Autowired, @Qualifier, @Primary

@Autowired: 自动注入

  • 默认优先按照 类型 去容器中找到对应的组件: applicationContext.getBean(BookDao.class); 找到就给bookDao赋值
  • 如果找到多个相同类型的组件,再将属性的名称作为组件的id去容器中查找
    applicationContext.getBean(“bookDao”)
  • @Qualifier("bookDao"): 使用@Qualifier指定需要装配的组件的id, 而不是使用属性名
  • 自动装配默认一定要将属性赋值好,否则就会报错; 可以使用@Autowired(required=false),如果没有找到对应要注入的bean,也不会报错
  • @Primary: 让Spring优先选择装配标注该注解的bean; 也可以继续使用@Qualifier指定需要装配的bean的名字
BookService {
    @Autowired
    BookDao bookDao;
}
2、@Resource, @Inject
  • 上面的@Autowird和@Qualifier是Spirng的注解, 除此之外Spring还支持java规范的注解, @Resource@Inject注解

@Resource: 可以和@Autowired一样实现自动装配的功能, 默认是按照组件名称进行装配的; 没有@Primary和@Qualifier的支持;

@Inject: 需要导入javax.inject的包,和@Autowired的功能一样. 没有required=false的功能;

注意: 开发中这三种自动装配的注解, 一般使用@Autowired就可以了

3、@RequiredArgsConstructor

在我们写controller或者Service层的时候,需要注入很多的mapper接口或者另外的service接口,这时候就会写很多的@Autowired注解,代码看起来很乱

  • lombok提供了一个注解:

@RequiredArgsConstructor(onConstructor =@_(@Autowired))
写在类上可以代替@Autowired注解,需要注意的是在注入时需要用final定义,或者使用@notnull注解
在这里插入图片描述

三、@Profile和@ActiveProfiles

跳转到目录

  • @Profile标签能够根据不同的运行环境,动态激活和切换一系列组件的功能, 可以通过@ActiveProfile来指定运行环境,

资源文件
db-dev.properties

db.username=zygui_dev
db.password=1234
db.url=https://blog.csdn.net/m0_37989980

db-test.properties

db.username=zygui_test
db.password=1234
db.url=https://blog.csdn.net/m0_37989980

DevConfig配置类

@Configuration
@PropertySource("classpath:db-dev.properties")
@Profile("dev")
public class DevConfig {
    @Bean
    public SomeBean someBean() {
        return new SomeBean();
    }
}

TestConfig配置类

@Configuration
@PropertySource("classpath:db-test.properties")
@Profile("test")
public class TestConfig {
    @Bean
    public OtherBean otherBean() {
        return new OtherBean();
    }
}

AppConfig配置类

@Configuration
@Import({DevConfig.class, TestConfig.class})
public class AppConfig {

    // @Value相当于 <property name="username" value="${db.username}"/>
    @Value("${db.username}")
    private String username;
    @Value("${db.password}")
    private String password;
    @Value("${db.url}")
    private String url;

    // 该bean是为了解析@Value中SpringEL表达式
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean
    public DataSource dataSource() {
        return new DataSource(username, password, url);
    }
}

AppTest测试类

  • 此时可以通过@ActiveProfiles("test")来灵活指定哪种环境;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class)
@ActiveProfiles("test")
public class AppTest {

	// 像ApplicationContext这些特殊的对象, 可以直接从Spring容器中注入成功
    @Autowired
    private ApplicationContext ctx;

    @Test
    public void test() {
        System.out.println(ctx.getBean(DataSource.class));
        try {
            System.out.println(ctx.getBean(SomeBean.class));
        } catch (Exception e) {
        }
        try {
            System.out.println(ctx.getBean(OtherBean.class));
        } catch (Exception e) {
        }
    }
}

AppTest2

public class AppTest2 {

    @Test
    public void test(){
        ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
        System.out.println(ctx.getBean(DataSource.class));
    }
}

要想使用上面做这种测试需要将spring.profiles.active作为环境变量;
在这里插入图片描述

spring.profiles.active设置位置:
1,作为SpringMVC中的DispatcherServlet的初始化参数
2,作为Web 应用上下文中的初始化参数
3,作为JNDI的入口
4,作为环境变量
5,作为虚拟机的系统参数
6,使用@ActiveProfile来进行激活

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

white camel

感谢支持~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值