1. Automation configuration
Package Com.springinaction.test;import Org.springframework.context.annotation.componentscan;import org.springframework.context.annotation.Configuration; @Configuration//Tell spring this is a configuration class @componentscan//scan component public Class Cdplayerconfig {}
Package Com.springinaction.test;import org.springframework.stereotype.Component; @Componentpublic class Sgtpeppers Implements COMPACTDISC{//COMPACTDISC is an interface private string title = "Sgt. Pepper ' linel Hearts cloub Band";p rivate string Art ist = "the Beatles"; @Overridepublic void Play () {System.out.println ("Playing" + title + "by" + artist);}
2. Java-based display configuration: To declare a bean in Java, we need a method
Package Com.springinaction.test;import Org.springframework.context.annotation.bean;import Org.springframework.context.annotation.Configuration, @Configurationpublic class Cdplayerconfig {@Bean//@ The bean will tell spring that this method will return an object to be registered as Beanpublic Compactdisc sgtpeppers () {return new sgtpeppers () in the spring application context;}}
Package Com.springinaction.test;import org.springframework.stereotype.component;//There is no OH public class sgtpeppers Implements Compactdisc{private string title = "Sgt. Pepper ' linel Hearts cloub Band";p rivate string artist = "The Beatles "; @Overridepublic void Play () {System.out.println (" Playing "+ title +" by "+ artist);}
3. XML-based display configuration
<?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/tx http://www.springframework.org/schema/tx/spring-tx.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop.xsd "><!-- Simple bean Reference--><bean id= "Compactdisc" class= "Com.springinaction.test.CompactDisc"/><bean id= "CDPlayer" class= "Com.springinaction.test.CdPlayer" > <!--constructor parameter is Compactdisc object-- > <constructor-arg ref= "Compactdisc"/> &nbsP;</bean></beans>
Regardless of the scanning approach, these techniques describe the components in the spring application and the relationships between these components;
It is recommended to use the automation configuration as much as possible to avoid the maintenance costs associated with the display configuration;
If you do need to display configuration spring, you should prioritize Java-based configuration, which is more powerful, type-safe, and easy to refactor than an XML-based configuration!
Three main ways to assemble beans in spring