Spring Java Based Config

The following app-context.xml

[sourcecode language=”xml”]
<?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”
xmlns:p=”http://www.springframework.org/schema/p”
xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd”>

<context:annotation-config/>

<bean id=”profile” class=”com.skills421.spring15.beans.Profile”/>

<bean id=”student1″ class=”com.skills421.spring15.beans.Student”
p:name=”John Doe”
p:age=”21″/>

<bean id=”student2″ class=”com.skills421.spring15.beans.Student”
p:name=”Jane Doe”
p:age=”19″/>

</beans>
[/sourcecode]

can be replaced with the following SpringConfig.java

[sourcecode language=”java”]
package com.skills421.spring16.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.skills421.spring16.beans.Profile;
import com.skills421.spring16.beans.Student;

@Configuration
public class SpringConfig
{
@Bean
public Profile profile()
{
return new Profile();
}

@Bean
public Student student1()
{
return new Student(“James Davinson”, 30);
}

@Bean
public Student student2()
{
return new Student(“Nicky Taylor”, 19);
}
}
[/sourcecode]

The MainApp.java code needs to be modified as follows:

[sourcecode language=”java”]
AbstractApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
ctx.registerShutdownHook();

Profile profile = (Profile) ctx.getBean(“profile”);

profile.printName();
profile.printAge();
[/sourcecode]

You will also need the CGLib jar

This can be added in the Pom as follows:

[sourcecode language=”xml”]
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
[/sourcecode]

or downloaded from cglib.sourceforge.net

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.