Spring根据XML配置文件 p名称空间注入属性的实例
发布时间:2020-05-23 15:22:02 所属栏目:Java 来源:互联网
导读:要生成对象并通过名称空间注入属性的类代码如下:packagecom.swift;publicclassUser{
|
要生成对象并通过名称空间注入属性的类 代码如下:
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,IOException {
doGet(request,response);
}
}
以上这篇Spring根据XML配置文件 p名称空间注入属性的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程小技巧。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- java – 当我们有坐标列表时,如何在JTS中创建一个多边形?
- java – 如何在Libgdx中旋转矩形?
- java – 没有在try / catch中捕获NumberFormatException
- Mybatis中的config.xml配置文件详细解析
- springboot注入servlet的方法
- java – 错误的密钥类:文本不是IntWritable
- java – 为什么不在这个JNI代码中显示select系统调用?
- java – Spring MVC忽略配置的PropertyEditor并改为使用构造
- Java和python进程可以独占锁定linux上的相同文件
- Android简易网络请求工具WebHttpHelper
