Spring根据XML配置文件 p名称空间注入属性的实例

网友投稿 259 2023-03-16


Spring根据XML配置文件 p名称空间注入属性的实例

要生成对象并通过名称空间注入属性的类 代码如下:

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配置文件写法如下:

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xmlns:p="http://springframework.org/schema/p"

xsi:schemaLocation="

http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans.xsd">

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xmlns:p="http://springframework.org/schema/p"

xsi:schemaLocation="

http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans.xsd">

p:userName="peach"

p:后是属性的变量名 后面是赋值

约束是xmlns:p="http://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);

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:React/Redux应用使用Async/Await的方法
下一篇:api接口文档免费模板(api接口文档是什么意思)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~