----A more streamlined version
Useraction.java
Import Javax.annotation.resource;import Org.springframework.stereotype.component;import org.springframework.stereotype.controller;//@Component ("useraction") //Join IOC container//@Component @controller The component of the control layer public class Useraction {@Resourceprivate userservice userservice;public String execute () {userservice.save (); return null;}}
Userservice.java
Import Javax.annotation.resource;import Org.springframework.stereotype.component;import org.springframework.stereotype.service;//@Component ("UserService") //UserService join IOC container//@ Component@service //Represents the component of the business Logic layer public class UserService {//@Resource// Find by Type "in the container to ensure that the type has only one variable" @Resource ( Name = "Userdao") //Find private Userdao Userdao by name; Go to the container to recruit the variable of type Userdao, after finding it, assign the value public void Save () {Userdao.save ();}}
Userdao.java
Import Org.springframework.stereotype.component;import org.springframework.stereotype.repository;//Add the current object to the IOC container/ /@Component ("Userdao") // equivalent to Bean.xml "<bean Id=userdao class=": "/>"//@Component // The reference name of the Userdao object that joins the IOC container, the default is the same as the class name, and the first letter is lowercase//@Repository //Can be selected in the persistence layer with this annotation public class Userdao {public Userdao () { System.out.println ("Userdao.userdao ()");} public Userdao (int id) {System.out.println ("Userdao.userdao (int id)" + ID);} public void Save () {System.out.println ("ZENGMG: Save user!!!");}}
Bean.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:p= "http://www.springframework.org/schema/p" 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/context http://www.springframework.org/schema/context/spring-context.xsd ><!--turn on annotation scanning--><context:component-scan base-package= "Zengmg.e_anno2" ></context:component-scan ><bean id= "Userdao" class= "ZENGMG. Userdao "scope=" prototype "></bean></beans>
Test Code:
Import Org.junit.test;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;public class App {//Create container object private ApplicationContext ac = new Classpathxmlapplicationcontext ("Zengmg/e_anno2/bean.xml"); @Testpublic void Testexecuteaction () {//get actionuseraction useraction = (useraction) ac.getbean ("Useraction") from the container; Useraction.execute ();}}
Spring IOC container-annotated Way "more simplified"