First, Applicationcontext.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" xsi:schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans/spring-beans.xsd "><!--Configure the Bean in the container file (service/dao/domain/action /data Source)-<!--bean element: When the spring framework loads, Spring automatically creates a bean object and puts it into memory UserService userservice=new userservice (); ID number corresponds to UserService userservice.setname= "Zhang San"-<bean id= "UserService" class= "Com.service.UserService" > <property name= "Name" > <value> Zhang San </value> </property> <!--reference B in UserService Yservice Bean The first Byeservice, which represents the property of UserService, the second represents a reference to <property name= "Byeservice" ref= "Byeserv Ice "></property> </bean> <bean id=" Byeservice "class=" Com.service.ByeService "> <property Name= "name" value= "Xiao Ming" ></property> ≪/bean></beans>
Second, Service
(a) UserService
public class UserService {private String name; Byeservice byeservice;public String getName () {return name;} public void SetName (String name) {this.name = name;} Public Byeservice Getbyeservice () {return byeservice;} public void Setbyeservice (Byeservice byeservice) {this.byeservice = Byeservice;} public void SayHello () {System.out.println ("hello~~~" +name); Byeservice.saybye ();}}
Two Byeservice
public class Byeservice {private string Name;public string GetName () {return name;} public void SetName (String name) {this.name = name;} public void Saybye () {System.out.println ("bye" +name);}}
Third, Test
public class Test {public static void main (string[] args) {//traditional method calls UserService SayHello method//userservice userservice=new UserService ();//userservice.setname ("Zhang San");//userservice.sayhello ();//Use spring to complete//1, Get spring's ApplicationContext object (container counterpart) ApplicationContext Ac=new Classpathxmlapplicationcontext (" Applicationcontext.xml "); UserService us= (UserService) Ac.getbean ("UserService"); Us.sayhello (); Using Util to get ApplicationContext
((UserService) Applicationcontextutil.getapplicationcontext (). Getbean ("UserService")). SayHello ();// AC stands for Container applicationcontext//byeservice bs= (byeservice) Ac.getbean ("Byeservice");//bs.saybye ();}}
Iv. Util
Final public class Applicationcontextutil {private static ApplicationContext ac=null;private Applicationcontextutil () {}static{ac=new classpathxmlapplicationcontext ("Applicationcontext.xml");} public static ApplicationContext Getapplicationcontext () {return AC;}}
(i) Introduction to Spring