Injecting object properties using the Set method
Writing Userdao.java files
1 Package com.example.spring; 2 3 Public class Userdao {4 Public void print () {5 System.out.println ("Dao print.") ); 6 }7 }
Writing Userservice.java files
1 Packagecom.example.spring;2 3 Public classUserService {4 //1. Defining DAO Type Properties5 PrivateUserdao Userdao;6 //2. Generate Set Method7 Public voidSetuserdao (Userdao Userdao) {8 This. Userdao =Userdao;9 }Ten One Public voidprint () { ASystem.out.println ("Service print.")); - //if you want to invoke the method inside DAO in the service without using Spring object property injection, you must first new DAO object - //Userdao dao = new Userdao (); the //dao.print (); - userdao.print (); - } -}
Writing beans.xml files
1 <?XML version= "1.0" encoding= "UTF-8"?>2 <Beansxmlns= "Http://www.springframework.org/schema/beans"3 Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"4 xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd ">5 6 <BeanID= "Userdao"class= "Com.example.spring.UserDao"></Bean>7 8 <BeanID= "UserService"class= "Com.example.spring.UserService" >9 < Propertyname= "Userdao"ref= "Userdao"></ Property>Ten </Bean> One </Beans>
Note the injected property is the ID of the Userdao class.
Writing Application.java
1 Packagecom.example.spring;2 3 ImportOrg.springframework.context.support.AbstractApplicationContext;4 ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;5 6 Public classApplication {7 Public Static voidMain (string[] args) {8 //Where the bean configuration file is located d:\\ideaprojects\\spring\\src\\beans.xml9 //using the Abstractapplicationcontext containerTenAbstractapplicationcontext context =NewClasspathxmlapplicationcontext ("File:d:\\ideaprojects\\spring\\src\\beans.xml"); One //get configuration-created objects AUserService UserService = (userservice) context.getbean ("UserService"); - userservice.print (); - } the}
Run output
Service Print. Dao Print.
Java Framework Spring Boot learning Note (ix): Injecting object Type properties