Previously, we defined beans in XML files, for example:
<Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation = "http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id = "hellobean" class = "com. mkyong. hello. impl. helloworldimpl "> </beans>
In fact, we can use annotations to accomplish these tasks, for example, the followingCodeThe completed functions are the same as those configured in XML:
Import Org. springframework. context. annotation. bean; import Org. springframework. context. annotation. configuration; import COM. mkyong. hello. helloworld; import COM. mkyong. hello. impl. helloworldimpl; @ configurationpublic class appconfig {@ Bean (name = "hellobean") Public helloworld () {return New helloworldimpl ();}}
Imagine a scenario where we have a large project. If we configure all the beans in an XML file, the file will be very large. In most cases, we split a large xml configuration file into several parts. This facilitates management. Finally, you can import the data to the total XML file, for example:
<Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation = "http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <import resource = "config/customer. XML "/> <import resource =" config/Scheduler. XML "/> </beans>
But now we can also use javaconfig to do the same job:
Import Org. springframework. context. annotation. configuration; import Org. springframework. context. annotation. import; @ configuration @ import ({customerconfig. class, schedulerconfig. class}) public class appconfig {}
Let's look at a demo for this example:
Customerbo. Java
Public class customerbo {public void printmsg (string MSG) {system. Out. println ("customerbo:" + MSG );}}
Schedulerbo. Java
Public class schedulerbo {public void printmsg (string MSG) {system. Out. println ("schedulerbo:" + MSG );}}
Now let's use Annotations:
@ Configurationpublic class customerconfig {@ Bean (name = "customer") Public customerbo () {return New customerbo ();}}
@ Configurationpublic class schedulerconfig {@ Bean (name = "scheduler") Public schedulerbo suchedulerbo () {return New schedulerbo ();}}
Appconfig. Java
Import Org. springframework. context. annotation. configuration; import Org. springframework. context. annotation. import; @ configuration @ import ({customerconfig. class, schedulerconfig. class}) public class appconfig {}
Then run:
Public class app {public static void main (string [] ARGs) {applicationcontext context = new annotationconfigapplicationcontext (appconfig. class); customerbo customer = (customerbo) context. getbean ("customer"); customer. printmsg ("Hello 1"); schedulerbo scheduler = (schedulerbo) context. getbean ("scheduler"); scheduler. printmsg ("Hello 2 ");}}