Spring injects attributes according to the XML configuration file p namespace, springxml
The class code for generating objects and injecting attributes through namespaces 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 is ready."+this.userName; }}
The XML configuration file is written as follows:
<? 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" xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <! -- IoC control inversion spring generates an object based on the XML configuration file --> <bean id = "user" class = "com. swift. user "p: userName =" peach "> </bean> </beans>
P: userName = "peach"
P: The variable name is followed by the value assignment.
The constraint is xmlns: p = "http://www.springframework.org/schema/p"
Call the method to generate objects and attribute values. The Code is as follows:
Package com. swift; import java. io. IOException; import javax. servlet. servletException; import javax. servlet. annotation. webServlet; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import org. springframework. context. applicationContext; import org. springframework. context. support. classPathXmlApplicationContext; @ WebServlet ("/test") public class TestIOC extends HttpServlet {private static final long serialVersionUID = 1L; public TestIOC () {super ();} protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response. getWriter (). append ("Served :"). append (request. getContextPath (); @ SuppressWarnings ("resource") // The following sentence: ApplicationContext context = new ClassPathXmlApplicationContext ("applicationContext. xml "); User user = (User) context. getBean ("user"); String userInfo = user. fun (); response. getWriter (). println (); response. getWriter (). append (userInfo);} protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response );}}