欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2021-04-22 09:13:40|栏目:JAVA代码|点击:

前言

在实际开发当中,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");

上一篇:java实现多人多牌数比较游戏

栏    目:JAVA代码

下一篇:MyBatis-Generator的配置说明和使用

本文标题:Spring注解驱动开发实现属性赋值

本文地址:http://www.codeinn.net/misctech/106526.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有