• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

详解Spring注解驱动开发之属性赋值

java 搞代码 4年前 (2022-01-05) 97次浏览 已收录 0个评论
文章目录[隐藏]

今天带大家学习Spring注解驱动开发的相关知识,文中有非常详细的代码示例,对正在学习Java的小伙伴们很有帮助,需要的朋友可以参考下

一、@Value注解

Person的属性上使用@Value注解指定注入值

 public class Person { @Value("#{20-2}")     //SpEL表达式 #{} private Integer id; @Value("张三")        //基本数据类型 private String name; } 

配置类

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

测试

 @Test public void testValues(){ ApplicationContext context = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class); String[] beanDefinitionNames = context.getBeanDefinitionNames(); for (String beanName : beanDefinitionNames){ System.out.println(beanName); } Person person = (Person) context.getBean("person"); System.out.println(person); } 

输出结果:

二、@PropertySource加载外部配置文件

配置类加上@PropertySource注解,引入外部配置文件

 @PropertySource({"classpath:/person.properties"}) @Configuration public class MainCo<strong style="color:transparent">来源gao@daima#com搞(%代@#码网</strong>nfigOfPropertyValues { @Bean public Person person(){ return new Person(); } } 

使用${属性值}注入属性值

 public class Person { @Value("#{20-2}")     //SpEL表达式 #{} private Integer id; @Value("张三")        //基本数据类型 private String name; @Value("${person.age}")     //使用外部配置文件注入属性值 private Integer age; } 

输出结果:

因为配置文件中的值默认都加载到环境变量中,所有还可以通过环境变量来获取配置文件中的值

 @Test public void testValues(){ ApplicationContext context = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class); String[] beanDefinitionNames = context.getBeanDefinitionNames(); for (String beanName : beanDefinitionNames){ System.out.println(beanName); } Person person = (Person) context.getBean("person"); System.out.println(person); Environment environment = context.getEnvironment(); String age = environment.getProperty("person.age"); System.out.println("age = " + age); } 

输出结果:

到此这篇关于详解Spring注解驱动开发实现属性赋值的文章就介绍到这了,更多相关Spring注解驱动开发内容请搜索gaodaima搞代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持gaodaima搞代码网

以上就是详解Spring注解驱动开发之属性赋值的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:详解Spring注解驱动开发之属性赋值

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址