Spring的@Value属性怎么赋值
本篇内容主要讲解“Spring的@Value属性怎么赋值”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Spring的@Value属性怎么赋值”吧!
成都创新互联专注于企业成都全网营销推广、网站重做改版、善右网站定制设计、自适应品牌网站建设、html5、商城系统网站开发、集团公司官网建设、成都外贸网站制作、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为善右等各大城市提供网站开发制作服务。
1.建立新的配置类
@Configurationpublic class MainConfigOfPropertyValues {@Beanpublic Person person(){return new Person();}}
2.建立新的测试方法
public class IOCTest_PropertyValue {AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);@Testpublic void test01(){printBeans(applicationContext);System.out.println("=============");Person person = (Person) applicationContext.getBean("person");System.out.println(person);}private void printBeans(AnnotationConfigApplicationContext applicationContext){String[] definitionNames = applicationContext.getBeanDefinitionNames();for (String name : definitionNames) {System.out.println(name);}}}

3.通过@Value 进行赋值
@Value("张三")private String name; @Value("#{20-2}")private Integer age; @Value("${person.nickName}")private String nickName; 
4.通过@PropertySource 加载配置文件,并进行注入
@PropertySource(value={"classpath:/person.properties"}) person.nickName=小李四
ConfigurableEnvironment environment = applicationContext.getEnvironment();String property = environment.getProperty("person.nickName");System.out.println(property); 
5.拓展@Value 、@PropertySource
@Value 静态变量赋值
在处理静态变量时候,使用上面的@Value的用法是无法获取到配置文件中的数据的,只能获取到null,所以要进行如下更改。
@PropertySource注解的地址可以是以下两种:
classpath路径:"classpath:/com/myco/app.properties"
文件对应路径:"file:/path/to/file"
到此,相信大家对“Spring的@Value属性怎么赋值”有了更深的了解,不妨来实际操作一番吧!这里是创新互联网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
分享文章:Spring的@Value属性怎么赋值
转载来源:http://www.jxjierui.cn/article/ggicph.html


咨询
建站咨询
