本系列开始Spring主要注解的介绍。 我们先从@Value开始, @Value和@Configuration和一起使用,读取属性文件。. @Value reads the property file. 属性文件可以通过应用的xml加载。下面的例子中,我们从应用的xml文件获得属性文件,然后通过@Value读取属性值,.
具体代码在这里,欢迎fork,加星,谢谢!
- @Configuration加载应用的xml文件
package com.yq.config;
import com.yq.domain.Bonus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration
@ImportResource("classpath:/appConf.xml")
public class AppConfig {
private @Value("#{entProp['bonus.name']}") String bonusName;
private @Value("#{entProp['bonus.time']}") long bonusTime;
private @Value("#{entProp['bonus.count']}") int bonusCount;
@Bean(name="bonus")
public Bonus bonus(){
Bonus bonus = new Bonus();
bonus.setName(bonusName);
bonus.setTime(bonusTime);
bonus.setCount(bonusCount);
return bonus;
}
}
- 应用的xml文件appConf.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<util:properties id="entProp" location="classpath:/bonus01.cfg" />
</beans>
可以看到我们设置了, 也就是有个propterties util对象,id是entProp, 我们可以 private @Value(“#{entProp[‘bonus.time’]}”) long bonusTime;从中读取属性
- 实体类,也就是我们要使用的bean对象的类
package com.yq.domain;
import lombok.Data;
@Data
public class Bonus {
private String name;
//奖金发放时间
private long time;
//奖金金额
private int count;
}
- 属性文件bonus01.cfg
bonus.name= Quarterly Award
bonus.time= 1530930688777
bonus.count= 1000
- 最后是,我们main类
package com.yq;
import com.yq.domain.Bonus;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class ValueMain {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(com.yq.config.AppConfig.class);
ctx.refresh();
Bonus bonus= (Bonus)ctx.getBean("bonus");
System.out.println(bonus.getName());
System.out.println(bonus.getTime());
System.out.println(bonus.getCount());
}
}
- 运行结果**
“…” com.yq.ValueMain
七月 07, 2018 10:33:47 上午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@1ed6993a: startup date [Sat Jul 07 10:33:47 CST 2018]; root of context hierarchy
七月 07, 2018 10:33:47 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [appConf.xml]
Quarterly Award
1530930688777
1000