How to have a non-XML(annotations) based configuration ?
First lets see an XML based configuration.
Book.java:
package com.heapsteep.model; public class Book { private String bookName; public void setBookName(String bookName) { this.bookName = bookName; } public String getBookName() { return bookName; } }
spring-servlet.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" 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"> <context:component-scan base-package="com.heapsteep"/> <bean id="book" class="com.heapsteep.model.Book" init-method="myPostConstruct" destroy-method="myPreDestroy"> <property name="bookName" value="Mahabharat"/> </bean> </beans>
SpringDemo.java:
package com.heapsteep; import org.springframework.context.ApplicationContext; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.heapsteep.model.Book; public class SpringDemo { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("spring-servlet.xml"); Book book = (Book)context.getBean("book"); System.out.println("Book Name:"+ book.getBookName()); } }
Just right-click on the SpringDemo.java and run as “java application”.
You will get the value from the book object.
Now lets convert the above codes to an non-XML(annotations) based configuration:
Book.java: (No changes)
package com.heapsteep.model; public class Book { private String bookName; public void setBookName(String bookName) { this.bookName = bookName; } public String getBookName() { return bookName; } }
Instead of the servlet-config.xml file we will keep a file – MyConfig.java.(We can remove this file as well and write the same snippet inside the calling file -“SpringDemo_WithoutXML.java” as well):
MyConfig.java:
@Configuration public class MyConfig { @Bean(name="book") public Book book() { Book book=new Book(); book.setBookName("Ramayana"); return book; } }
SpringDemo_WithoutXML.java:
public class SpringDemo_WithoutXML { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class); Book book = (Book)context.getBean("book"); System.out.println("Book Name>>>:"+ book.getBookName()); } }
Right-click on the SpringDemo_WithoutXML.java and run as Java application.
You will get the respective value of the book bean.
What is the difference between @Bean and @Component in Spring ?
So guys…. in this tutorial we saw how to configure a bean in xml and do the same without an xml, i.e, by annotations.
Hope you enjoyed the tutorial….