Searching...
Monday, 18 March 2013

Spring Core- Creating beans example

12:23

 

There are two ways we can create beans spring

1.XML Based
Create xml configuration for denfining beans
2.Annotation based
Create annotation based java configuration class to create beans

Note: In this example creating beans for a simple Student object
1. XML Based configuration
<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-2.5.xsd">

    <bean id="studentBean" class="com.vinod.test.Student">
    </bean>
</beans>
2. Annotation based configuration
package com.vinod.test;

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

@Configuration
public class SpringCoreConfig {
    @Bean
    public Student getStudentBean() {
        Student stud = new Student();
        stud.setName("Vinod");
        return stud;
    }
}
3. Student.java
package com.vinod.test;

public class Student {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
3. Test class
package com.vinod.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringCoreMain {

    public static void main(String[] args) {

        // Getting beans from XML based bean configuration
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-core.xml");
        // Student bean
        Student obj = (Student) context.getBean("studentBean");
        obj.setName("vinod");
        System.out.println(obj.getName());

        // Getting beans from Annotaion based configuration

        AnnotationConfigApplicationContext anno = new AnnotationConfigApplicationContext();
        anno.register(SpringCoreConfig.class);
        anno.refresh();
        Student stu = anno.getBean(Student.class);
        System.out.println(stu.getName());
    }

}
4. Output
vinod
Vinod

0 comments: