Monday, August 13, 2007

Inject a String with Spring 2.0.6 and Maven2

Here's a real quick how-to for injecting a simple String value with Spring 2.0.6.

Configuration File


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC
"-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
<bean id="proxyHost" class="java.lang.String">
<constructor-arg>
<value>10.9.5.120</value>
</constructor-arg>
</bean>
</beans>


Java Code

public class stringInjectionExample {
private static final String SPRING_FILE = "sip.xml";
private static final String PROXY_HOST_BEAN_NAME = "proxyHost";

public void init() {
Resource resource = new ClassPathResource(SPRING_FILE);
BeanFactory factory = new XmlBeanFactory(resource);
String proxyHost = (String) factory.getBean(PROXY_HOST_BEAN_NAME);

System.out.println("Using ProxyHost: " + proxyHost);
}
}


Output

Using ProxyHost: 10.9.5.120


pom.xml

...

<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>2.0.6</version>
</dependency>
</dependencies>

<repositories>
<repository>
<id>Ibiblio</id>
<name>Maven2 Ibiblio Repository</name>
<url>http://mirrors.ibiblio.org/pub/mirrors/maven2</url>
<layout>default</layout>
</repository>
</repositories>

...

1 comment:

jlorenzen said...

First you need to change the width of your blog. Its not wide enough; I can't see all your code.
Second, great example, but to take it to the next step you need to make the value in the spring file configurable, say using a maven property that is set in the user's settings xml file. Similiar to maven1 build.properties file in the user.home dir.