Spring 获取 bean xml 的 property

例如 获取下面示例的 name: maker,查到两种方法,虽然最终没有使用(发现是伪需求,其它地方有,不用从xml中获取),记录于此,或许有用到的时候。

1
2
3
<bean id="hi" class="spring.HelloWorld">
<property name="name" value="maker"/>
</bean>

方案一:

来源 https://blog.csdn.net/linkingfei/article/details/78677004

1
2
3
4
5
6
7
8
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("beans.xml");
BeanFactory factory=new XmlBeanFactory(r);
HelloWorld hi=(HelloWorld)factory.getBean("hi");
hi.show()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Test {
public static void main(String[] args) {
HelloWorld hi=new HelloWorld();
String name="";
Properties pt=new Properties();
try {
//注:有/为src目录下,无则为包目录下
pt.load(Test.class.getResourceAsStream("/Name.properties"));
name=pt.getProperty("name");
} catch (IOException e) {
e.printStackTrace();
}
hi.setName(name);
hi.show();
}
}

###方案二:
来源 https://stackoverflow.com/questions/19970605/how-to-get-the-property-value-inside-a-spring-bean-class-in-my-class

示例源码:

1
2
3
<bean id="dataSource" class="org.tempuri.DataBeanClass">
<property name="url" value="${url}"></property>
</bean>

You can annotate your bean property like this, then spring will auto inject the property from your property file.

1
2
@Value("${url}")  // @Value("#{dataSource.url}")
private String url;