gpt4 book ai didi

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

转载 作者:qq735679552 更新时间:2022-09-28 22:32:09 25 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章Spring根据XML配置文件 p名称空间注入属性的实例由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

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

?
1
2
3
4
5
6
7
8
9
10
11
12
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配置文件写法如下:

?
1
2
3
4
5
6
7
8
9
<? 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" 。

生成对象及属性值调用方法,代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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名称空间注入属性的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我.

原文链接:http://www.cnblogs.com/qingyundian/archive/2017/11/15/7840720.html 。

最后此篇关于Spring根据XML配置文件 p名称空间注入属性的实例的文章就讲到这里了,如果你想了解更多关于Spring根据XML配置文件 p名称空间注入属性的实例的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com