Example on howto use Spring.
This text covers the changes from
IoC example when to use Spring instead of
PicoContainer.
Spring needs a setter for the UserManager (UM) so it can satisfy this dependency. The constructor like in
IoC example is not needed.
public class AuthenticationService {
private UserManager manager; public setUserManager(UserManager manager) {
this.manager = manager;
} public boolean authenticate(String name, String password) {
if (manager.exists(name)) {
User user = manager.get(name);
return user.getPassword().equals(password);
} else {
return false;
}
}
}The recommended way to use Spring is to define dependencies with a an XML file
beans.xml:
<beans>
<bean id="authenticationService" class="example.AuthenticationService">
<property name="userManager"><ref bean="simpleUserManager"/></property>
</bean>
<bean id="simpleUserManager" class="example.SimpleUserManager"/>
</beans>To use our AuthenticationService, you do:
BeanFactory beanFactory =
new XmlBeanFactory(getClass().getResourceAsStream("/beans.xml"));// just bean factory reference from now on
// so the factory is also exchangeable
AuthenticationService as =
(AuthenticationService) beanFactory.getBean("authenticationService");
System.out.println("stephan.authenticated = " +
as.authenticate("stephan", "stephan"));
System.out.println("leo.authenticated = " +
as.authenticate("leo", "wrong"));The nice thing is that AS get's the UM that's available, SUM in this example. If we would change "SimpleUserManager" to "LDAPUserManager" then AS would get the LDAP manager for getting users. Easily exchangeable.
Java defined components
If you want to define component dependencies with Java instead of XML, this can be done in Spring with:
ListableBeanFactoryImpl beanFactory = new ListableBeanFactoryImpl();
MutablePropertyValues asPvs = new MutablePropertyValues();
asPvs.addPropertyValue("userManager",
new RuntimeBeanReference("simpleUserManager"));
beanFactory.registerBeanDefinition("authenticationService",
new RootBeanDefinition(AuthenticationService.class, asPvs, true));
beanFactory.registerBeanDefinition("simpleUserManager",
new RootBeanDefinition(SimpleUserManager.class, null, true));
// just bean factory reference from now on, same as before
...
Resources