java xml名称空间_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://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">

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名称空间注入属性的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值