The class code to build the object and inject the property through the namespace is as follows:
Package Com.swift; Public class User { private String userName; Public void setusername (String userName) { this. userName = userName; } Public String Fun () { return "User's fun was ready." +this. userName; }}
The XML configuration file is written as follows:
<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xmlns:p= "http://www.springframework.org/schema/p"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd "><!--IoC Control inversion Springspring object generation based on XML configuration file -<BeanID= "User"class= "Com.swift.User"P:username= "Peach"></Bean></Beans>
P:username= "Peach"
P: After the variable name of the property is assigned
Constraint is xmlns:p= "http://www.springframework.org/schema/p"
Generate object and property value call method, code as follows:
PackageCom.swift;Importjava.io.IOException;Importjavax.servlet.ServletException;ImportJavax.servlet.annotation.WebServlet;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext; @WebServlet ("/test") Public classTestiocextendsHttpServlet {Private Static Final LongSerialversionuid = 1L; PublicTestioc () {Super(); } protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {response.getwriter (). Append ("Served at:"). Append (Request.getcontextpath ()); @SuppressWarnings ("Resource") //that's the bottom line.ApplicationContext context=NewClasspathxmlapplicationcontext ("Applicationcontext.xml"); User User= (user) Context.getbean ("user")); String UserInfo=User.fun (); Response.getwriter (). println (); Response.getwriter (). append (UserInfo); } protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {doget (request, response); }}
Spring injects attributes based on the XML configuration file p namespace