In Spring 3.0 using the tag context:component-scan in xml file, the entry of the class(or bean) defined under the scan tag is automatically created. The example to show use of context:component-scan tag is as below:
Example:-
JavaConfig.java
package com.babita;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JavaConfig {
public void printMessage()
{
System.out.println("Hello World From Spring 3.0");
}
}
Now define the below code in app-context.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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.babita"></context:component-scan>
<context:annotation-config/>
</beans>
Now define the below class to run the code:
MainApp.java
package com.babita;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//ApplicationContext context = new AnnotationConfigApplicationContext();
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"app-context.xml"});
JavaConfig obj = (JavaConfig) context.getBean("javaConfig");
obj.printMessage();
}
}
In Above example we can see that the @Configuration Class JavaConfig.java can be instantiate using the following tag in app-context.xml file.this class(or bean) entry is automatically created in the xml file.
<context:component-scan base-package="com.babita"></context:component-scan>
Hope this will help you :)
0 Comment(s)