欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-12 09:31:07
要生成对象并通过名称空间注入属性的类 代码如下: 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名称空间注入属性的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。