Spring @Value的用法

@Value注解

Spring不仅可以通过xml配置获取*.properties,还可以通过@Value注解的方式来获取。

项目结构

项目结构

Spring配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.net"/>
<!-- 指定属性文件位置 -->
<context:property-placeholder location="classpath:*.properties"
ignore-unresolvable="true"/>
</beans>
属性文件
1
2
admin.username=admin
admin.password=123456
示例代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.net;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;
@Service
public class Main {
@Value("${admin.username}")
private String adminName;
@Value("${admin.password}")
private String adminPassword;
public String getAdminName() {
return adminName;
}
public String getAdminPassword() {
return adminPassword;
}
public static void main(String[] args){
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
Main p=context.getBean(Main.class);
System.out.println(p.getAdminName());
System.out.println(p.getAdminPassword());
}
}
测试结果
1
2
admin
123456