Wednesday, 15 August 2012

Spring

Spring Wiring

To begin wiring spring beans together we need to create an applicationContext.xml. That looks like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
 default-autowire="byType">

 <bean id="knight" class="com.aphexmunky.spring.BraveKnight"/>
 
 <bean id="quest" class="com.aphexmunky.spring.Quester" />

</beans>

With these two beans explicitly wired, we can create spring and grab our beans out of it.

1
2
ApplicationContext ac = new ClassPathXmlApplicationContext("application.xml");
Knight knight = ac.getBean(Knight.class);

Autowiring

Autowiring can be done by annotating a private member with @Autowired. For this to work however the bean still needs to be defined.

However, there is spring context which can allow us to find beans automatically. The following needs to be added to the spring config file.

<?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"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
 default-autowire="byType">

 <context:component-scan base-package="com.aphexmunky.spring" />

</beans>

With this configuration, we've added spring context to the xml namespace and added context:component-scan which allows spring to find beans annotated with certain annotations and automatically consider them beans. They are

  • @Component
  • @Controller
  • @Repository
  • @Service

With these, any bean annotated with one and in the base-package specified can now be instantiated by spring.


spring xsd locations

No comments:

Post a Comment