zoukankan      html  css  js  c++  java
  • Spring根据XML配置文件 p名称空间注入属性(property后出现,简便但只针对基本数据类型管用,自定义集合等引用类型无效)

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

    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);
        }
    
    }
  • 相关阅读:
    jq实现简单的二级联动下拉框
    jq实现多选框及反选
    用js和css实现选项卡效果+jq(2019-10-09)
    python 创建类的实例对象
    selenium——获取元素的尺寸、文本信息、元素的属性、元素是否可见
    selenium——表单嵌套
    selenium控制浏览器
    类的应用
    零散的python知识点
    安装python2、python3
  • 原文地址:https://www.cnblogs.com/qingyundian/p/7840720.html
Copyright © 2011-2022 走看看