Study Address: https://www.w3cschool.cn/wkspring/rw2h1mmj.html
@Autowired notes
@Autowired annotations provide more granular control over where and how automatic connections are completed.
The @autowired in Setter method
Spellchecker.java:
Package com.lee.autowired; Public class spellchecker { public spellchecker () { System.out.println ("Inside spellchecker Constructor "); } Public void checkspelling () { System.out.println ("Inside checkspelling");} }
Texteditor.java:
Packagecom.lee.autowired;Importorg.springframework.beans.factory.annotation.Autowired; Public classTextEditor {Privatespellchecker spellchecker; Publicspellchecker Getspellchecker () {returnspellchecker; } @Autowired Public voidSetspellchecker (spellchecker spellchecker) { This. Spellchecker =spellchecker; } Public voidspellcheck () {spellchecker.checkspelling (); }}
Mainapp.java:
Packagecom.lee.autowired;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext; Public classMainapp { Public Static voidMain (string[] args) {ApplicationContext context=NewClasspathxmlapplicationcontext ("Beans2.xml"); TextEditor TD= (TextEditor) context.getbean ("TextEditor"); Td.spellcheck (); }}
Beans2.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.xsdhttp//Www.springframework.org/schema/contexthttp//www.springframework.org/schema/context/spring-context-3.0.xsd "><context:annotation-config/> <bean id= "TextEditor"class= "Com.lee.autowired.TextEditor" ></bean> <bean id= "spell"class= "Com.lee.autowired.SpellChecker" ></bean></beans>
The @autowired property in the
Only TextEditor are different:
PackageCom.lee.autowired2;Importorg.springframework.beans.factory.annotation.Autowired; Public classTextEditor {@AutowiredPrivatespellchecker spellchecker; PublicTextEditor () {System.out.println ("Inside TextEditor Constructor"); } Publicspellchecker Getspellchecker () {returnspellchecker; } Public voidspellcheck () {spellchecker.checkspelling (); }}
The @autowired property in the constructor
PackageCom.lee.autowired2;Importorg.springframework.beans.factory.annotation.Autowired; Public classTextEditor {Privatespellchecker spellchecker; @Autowired PublicTextEditor (spellchecker spellchecker) { This. spellchecker=spellchecker; System.out.println ("Inside TextEditor Constructor"); } Public voidspellcheck () {spellchecker.checkspelling (); }}
@autowired of Spring annotation-based configuration