Spring根据XML配置文件 p名称空间注入属性的实例
更新时间:2017年11月16日 09:03:18 作者:Advancing-Swift
下面小编就为大家分享一篇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配置文件写法如下:
<?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名称空间注入属性的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
SpringBoot使用过滤器、拦截器和监听器的案例代码(Springboot搭建java项目)
这篇文章主要介绍了SpringBoot使用过滤器、拦截器和监听器(Springboot搭建java项目),本文是基于Springboot搭建java项目,结合案例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2023-02-02
spring boot validation参数校验与分组嵌套各种类型及使用小结
参数校验基本上是controller必做的事情,毕竟前端传过来的一切都不可信,validation可以简化这一操作,这篇文章主要介绍了spring boot validation参数校验分组嵌套各种类型及使用小结,需要的朋友可以参考下2023-09-09
springboot中通过jwt令牌校验及前端token请求头进行登录拦截实战记录
这篇文章主要给大家介绍了关于springboot中如何通过jwt令牌校验及前端token请求头进行登录拦截的相关资料,需要的朋友可以参考下2024-08-08
Java TimeoutException:服务调用超时异常的正确解决方案
在现代软件开发中,服务间通信是构建分布式系统的基础,然而,网络延迟、服务负载、资源竞争等因素都可能导致服务调用超时,TimeoutException是Java中表示服务调用超时的常见异常之一,本文将探讨TimeoutException的成因及解决方案,需要的朋友可以参考下2024-12-12


最新评论