1. 程式人生 > >Spring根據XML配置文件 p名稱空間註入屬性

Spring根據XML配置文件 p名稱空間註入屬性

javax ons oid 反轉 frame classpath mls xml配置 ng-

要生成對象並通過名稱空間註入屬性的類 代碼如下:

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;
    }
}

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" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--
IoC 控制反轉 SpringSpring根據XML配置文件生成對象 --> <bean id="user" class="com.swift.User" p:userName="peach"></bean> </beans>
p:userName="peach"
p:後是屬性的變量名 後面是賦值
約束是
xmlns:p="http://www.springframework.org/schema/p"

生成對象及屬性值調用方法,代碼如下:

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 at: ").append(request.getContextPath()); @SuppressWarnings("resource") //就是下邊這幾句了 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); } }

Spring根據XML配置文件 p名稱空間註入屬性