If you want to set your Spring bean’s property value in bean configuration file, you can use below methods.
- Use property tag under bean tag.
<bean id="beanPropsInjection" name="beanPropsInjection" class="com.dev2qa.example.spring.BeanPropertiesInjection"> <property name="loginUserName" value="dev2qa.com"></property> <property name="loginPassword" value="dev2qa.com"></property> </bean>
- Use bean tag attribute prefixed with p schema. But before do below configuration, you should add namespace
xmlns:p="http://www.springframework.org/schema/p"
in the configuration file at first.<bean id="beanPropsInjection" name="beanPropsInjection" class="com.dev2qa.example.spring.BeanPropertiesInjection" p:loginUserName="dev2qa.com" p:loginPassword="dev2qa.com" />
Below will show you how to do this with Eclipse Spring IDE by examples.
1. Use bean sub tag property.
- Open Eclipse and create a Spring project. You can read Spring Hello World Example Use Maven And Eclipse to learn more.
- Create a java class with two properties
loginUserName
andloginPassword
.
BeanPropertiesInjection.java
package com.dev2qa.example.spring; public class BeanPropertiesInjection { private String loginUserName = ""; private String loginPassword = ""; public String getLoginUserName() { return loginUserName; } public void setLoginUserName(String loginUserName) { this.loginUserName = loginUserName; } public String getLoginPassword() { return loginPassword; } public void setLoginPassword(String loginPassword) { this.loginPassword = loginPassword; } }
- Add
BeanPropertiesInjection
insrc / main / resources / BeanSettings.xml
file.
Double clickBeanSettings.xml
file in left panel, click beans tab in right bottom panel, click “New Bean …” button.
- In popup dialog, input bean id, name and browse the class we just created.
- Click Next, in next wizard add bean properties, all properties are auto prompt when you input part character of property.
- Click Finish button, you can see below picture.
- Click the bottom Source tab, you can see the configuration xml source code as below.
2. Use bean attribute with name space “p”.
Below is the step to use name space “p” to specify a bean property’s value.
- Click bottom Namespaces tab and select the checkbox before p to add namespace in bean configuration file.
- Click the bottom Source tab, you can see the namespace has been added in it.
- Now you can edit the cnfiguration xml source manually to use namespace p to define the property and it’s value.
(Visited 349 times, 1 visits today)