温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring注解驱动开发实现属性赋值的方法

发布时间:2020-08-03 11:52:37 来源:亿速云 阅读:108 作者:小猪 栏目:编程语言

这篇文章主要讲解了Spring注解驱动开发实现属性赋值的方法,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

前言

在实际开发当中,Spring中bean的属性直接赋值用的不是太多,整理这方面的资料,做一个小结,以备后续更深入的学习。

通过配置文件的方式

以配置文件的方式启动spring容器时,可以使用property标签的value给bean的属性赋值,赋值的形式有以下几种:

<--通过context:property-placeholder将properties文件中的值加载的环境变量中(properties中的属性值最终是以环境变量的形式存储的)>
<context:property-placeholder location="classpath:person.properties"/> 
 <bean id="person" class="com.atneusoft.bean.Person" >
    <--①通过基本数值直接赋值-->
    <property name="name" value="zhangsan"></property>
    <--②通过${}取出配置文件中的值-->
    <property name="age" value="${person.age}"></property>
     <--③通过Spring的El表达式-->
     <--<property name="age" value="10*2"></property>-->
</bean>

classpath下的properties文件内容

person.age=\u5C0F\u674E\u56DB

通过注解的方式

使用properties的value对应的注解给属性赋值

//使用@PropertySource读取外部配置文件中的k/v保存到运行的环境变量中;加载完外部的配置文件以后使用${}取出配置文件的值
@PropertySource(value={"classpath:/person.properties"})
@Configuration
public class MainConfigOfPropertyValues {
  @Bean
  public Person person(){
    return new Person();
  }
}
public class Person {
  
  //使用@Value赋值;
  //1、基本数值
  //2、可以写SpEL; #{}
  //3、可以写${};取出配置文件【properties】中的值(在运行环境变量里面的值)
  
  @Value("张三")
  private String name;
  @Value("#{20-2}")
  private Integer age;
  
 /* @Value("${person.age}")  private Integer age;*/
}

注:

外部配置文件中的k/v保存到运行的环境变量中,可以直接在环境变量中取出对应的值

AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);
ConfigurableEnvironment environment = applicationContext.getEnvironment();
String property = environment.getProperty("person.age");

看完上述内容,是不是对Spring注解驱动开发实现属性赋值的方法有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI