【Spring注解】3、属性赋值

版权声明:本文为博主原创文章,未经博主允许不得转载。请联系博主或者emailTo:[email protected],谢谢! https://blog.csdn.net/caychen/article/details/83009845

1、@Value

配置文件 person.properties:

person.nickName=张三
person.age=20

实体类 Person.java:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {

	/**
	 * 使用@Value赋值
	 * 	1、基本数值类型和String
	 * 	2、SpEL表达式: #{}
	 * 	3、${}: 取出配置文件中的值
	 * 
	 */
	
	@Value("${person.nickName}")
	private String name;
	
	@Value("${person.age}")
	private Integer age;
	
}

配置类 MyConfigOfPropertyValue.java

@PropertySources({
	@PropertySource(value="classpath:/person.properties")
})
@Configuration
public class MyConfigOfPropertyValue {

	@Bean
	public Person person() {
		return new Person();
	}
}

2、@Autowired、@Qualifier、@Primary、@Resource、@Inject

  • @Autowired

    • 默认优先按照类型去容器中找对应的组件;

    • 如果找到多个相同类型的组件,则再按照属性的名称作为组件的id去容器中查找;

  • @Qualifier

    • 使用@Qualifier指定需要装配的组件id,而不再使用属性名;

  • @Primary

    • 让Spring进行自动装配的时候,默认使用首选的Bean;

  • @Resource

    • 可以和@Autowired注解一样,实现自动装配功能,默认是按照组件名称进行装配的;

    • 也可以使用注解的name属性来使用指定的Bean;

    • 但是不能支持@Primary功能,也不支持@Autowired的required属性;

  • @Inject

    • 需要导入javax.inject的依赖包;

    • 可以和@Autowired注解一样,实现自动装配功能,但是不支持required属性;

该小节的例子就不再一一列举了,相信大家对其也是相当熟练了。

3、Spring底层组件

自定义组件实现xxxAware接口,在创建对象的时候,会调用接口规定的方法注入相关的组件,从而把Spring底层的一些组件注入到自定义的组件中。

  • ApplicationContextAware

    • 用于获取ApplicationContext

  • BeanFactoryAware

    • 用于获取BeanFactory

  • BeanNameAware

    • 用于获取BeanName

  • EmbeddedValueResolverAware

    • 用于获取StringValueResolver

  • ...

 

4、@Profile

@Profile:指定组件在某种环境下才能激活并注册到容器中,不指定的话,任何环境都能注册该组件。它由Spring提供,可以根据当前环境,动态的激活和切换一系列组件的功能。

  • 加了环境标识的Bean,只有在指定的环境被激活的情况下才能注册到容器中,默认环境是default;

  • 写在配置类上,只有在指定环境的时候,整个配置类里面的所有配置才能生效;

  • 没有标注环境标识的Bean,在任何环境下都是加载的。

@Configuration
public class MyConfigOfProfile implements EmbeddedValueResolverAware{

	@Value("${db.user}")
	private String user;
	
	private String driverClass;
	
	@Bean
	@Profile(value="test")
	public DataSource dataSourceTest(@Value("${db.password}")String password) throws Exception{
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		dataSource.setUser(user);
		dataSource.setPassword(password);
		dataSource.setJdbcUrl("jdbc:mysql:///test");
		dataSource.setDriverClass(driverClass);
		return dataSource;
	}
	
	@Bean
	@Profile(value="dev")
	public DataSource dataSourceDev(@Value("${db.password}")String password) throws Exception{
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		dataSource.setUser(user);
		dataSource.setPassword(password);
		dataSource.setJdbcUrl("jdbc:mysql:///mybatis");
		dataSource.setDriverClass(driverClass);
		return dataSource;
	}
	
	@Bean
	@Profile(value="prod")
	public DataSource dataSourceProd(@Value("${db.password}")String password) throws Exception{
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		dataSource.setUser(user);
		dataSource.setPassword(password);
		dataSource.setJdbcUrl("jdbc:mysql:///ssm");
		dataSource.setDriverClass(driverClass);
		return dataSource;
	}

	@Override
	public void setEmbeddedValueResolver(StringValueResolver resolver) {
		// TODO Auto-generated method stub
		this.driverClass = resolver.resolveStringValue("${db.driverClass}");
	}
	
}

注:为了配合多种注入的方式,所以代码采用了不同的注入方式来写这个配置类。

设置环境标识的方式:

  • 使用虚拟机参数:-Dspring.profiles.active=...
@Test
public void test1() {
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(
        MyConfigOfProfile.class);

    String[] beanNamesForType = applicationContext.getBeanNamesForType(DataSource.class);
    Arrays.asList(beanNamesForType).stream().forEach(System.out::println);
}
  • 使用代码修改环境标识:
@Test
public void test2() {
    // 创建applicationContext
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
    // 设置需要激活的环境
    applicationContext.getEnvironment().setActiveProfiles("test", "dev");
    // 设置主配置类
    applicationContext.register(MyConfigOfProfile.class);
    // 启动刷新
    applicationContext.refresh();

    String[] beanNamesForType = applicationContext.getBeanNamesForType(DataSource.class);
    Arrays.asList(beanNamesForType).stream().forEach(System.out::println);
}

====================打个广告,欢迎关注====================

QQ:

412425870

微信公众号:Cay课堂

csdn博客:

http://blog.csdn.net/caychen

码云:

https://gitee.com/caychen/

github:

https://github.com/caychen

点击群号或者扫描二维码即可加入QQ群:

328243383(1群)

 

点击群号或者扫描二维码即可加入QQ群:
180479701(2群)

--------------------- 作者:caychen 来源:CSDN 原文:https://blog.csdn.net/caychen/article/details/83009432?utm_source=copy 版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/caychen/article/details/83009845
今日推荐