当前位置: 移动技术网 > IT编程>开发语言>Java > Spring根据XML配置文件 p名称空间注入属性的实例

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

2019年07月19日  | 移动技术网IT编程  | 我要评论
要生成对象并通过名称空间注入属性的类 代码如下: package com.swift; public class user { private stri

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

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

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网