需要用到Spring压缩包中的四个核心JAR包

beans 、context、core 和expression

下载地址:

https://pan.baidu.com/s/1qXLHzAW

以及日志jar包

commons-logging 和log4j

下载地址:

https://pan.baidu.com/s/1mimTW5i


创建一个Dynamic Web Project 动态Web项目,在src中建立一个测试的类User如下:

package com.swift;

public class User {
public void fun() {
System.out.println("fun is ready.");
}
}

原始的方法是在main()中 User user=new User(); user.fun();

现在交给Spring帮我们创建对象,它的底层会使用反射机制等,我们只需要配置xml文件就可以了。

在src下建立applicationContext.xml

添加schema约束,文件代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> </beans>

配置对象创建

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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"></bean>
</beans>

创建Servlet类观察结果

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);
} }
//就是下边这几句了
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");//解析xml
User user=(User) context.getBean("user");//得到对象
String userInfo=user.fun();//使用对象
response.getWriter().append(userInfo);//服务器输出

注意,如果User类中写了有参构造,而找不到无参构造,则<bean id="user" class="com.swift.User"></bean>这种约束会失败,无法成功创建对象,所以要加上无参构造,代码如下
package com.swift;

public class User {
private String userName;
public User(String s) {
this.userName=s;
}
public User() {} public String fun() {
return "User's fun is ready.";
}
}

换一种方法,使用静态工厂的方法

package com.swift;

public class BeanFactoryUser {
public static User getUser() {
return new User();
}
}

类名.加static的方法——静态工厂的方法

这时xml配置文件增加

<bean id="beanFactory" class="com.swift.BeanFactoryUser" factory-method="getUser"></bean>

把静态方法也填上

Servlet类的代码如下:

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("/test2")
public class TestIOCServlet2 extends HttpServlet {
private static final long serialVersionUID = 1L;
public TestIOCServlet2() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
User user=(User) context.getBean("beanFactory");
String s=user.fun();
response.getWriter().println(s);
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
} }

实例工厂的方法

package com.swift;

public class FactoryInstance {
public User fun() {
return new User();
}
}

只有这么个非静态的方法,怎么通过xml配置文件得到User对象呢?

也是可以的

配置文件如下写法

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- IoC 控制反转 SpringSpring根据XML配置文件生成对象 -->
<bean id="factoryInstance" class="com.swift.FactoryInstance"></bean>
<bean id="user2" factory-bean="factoryInstance" factory-method="getUser"></bean>
</beans>

Servlet类实现结果

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("/test3")
public class TestIOCServlet3 extends HttpServlet {
private static final long serialVersionUID = 1L; public TestIOCServlet3() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
User user=(User) context.getBean("user2");
String s=user.fun();
response.getWriter().append(s);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
} }

User user1=(User) context.getBean("user2");

User user2=(User) context.getBean("user2");

得到的user1和user2是同一个对象,因默认情况下xml配置文件中是sigleton的单例模式

相当于<bean id="user" class="com.swift.User" scope="singleton"></bean>

多实例的对象模式——prototype(原型)

<bean id="user" class="com.swift.User" scope="prototype"></bean>

												

commons-logging 和log4j包下载 Spring根据XML配置文件生成对象的更多相关文章

  1. Spring根据XML配置文件注入对象类型属性

    这里有dao.service和Servlet三个地方 通过配过文件xml生成对象,并注入对象类型的属性,降低耦合 dao文件代码: package com.swift; public class Da ...

  2. Spring根据XML配置文件注入属性 其实也是造bean,看看是使用constructor还是setter顺带完成属性赋值

    方法一使用setter方法 package com.swift; public class Book { private String bookName; public void setBook(St ...

  3. Spring 通过XML配置文件以及通过注解形式来AOP 来实现前置,环绕,异常通知,返回后通知,后通知

    本节主要内容: 一.Spring 通过XML配置文件形式来AOP 来实现前置,环绕,异常通知     1. Spring AOP  前置通知 XML配置使用案例     2. Spring AOP   ...

  4. JavaWeb_(Spring框架)xml配置文件

    系列博文 JavaWeb_(Spring框架)xml配置文件  传送门 JavaWeb_(Spring框架)注解配置 传送门 Xml配置 a)Bean元素:交由Spring管理的对象都要配置在bean ...

  5. [error] eclipse编写spring等xml配置文件时只有部分提示,tx无提示

    eclipse编写spring等xml配置文件时只有<bean>.<context>等有提示,其他标签都没有提示 这时就需要做以下两步操作(下面以事务管理标签为例) 1,添加命 ...

  6. Spring框架xml配置文件 复杂类型属性注入——数组 list map properties DI dependency injection 依赖注入——属性值的注入依赖于建立的对象(堆空间)

    Person类中的各种属性写法如下: package com.swift.person; import java.util.Arrays; import java.util.List; import ...

  7. 如何配置多个Spring的xml配置文件(多模块配置)

    如何使用多个Spring的xml配置文件(多模块配置) (2009-08-22 13:42:43)   如何使用多个Spring的xml配置文件(多模块配置) 在用Struts Spring Hibe ...

  8. Spring 在 xml配置文件 或 annotation 注解中 运用Spring EL表达式

    Spring  EL 一:在Spring xml 配置文件中运用   Spring EL Spring EL 采用 #{Sp Expression  Language} 即 #{spring表达式} ...

  9. spring读取xml配置文件(二)

    一.当spring解析完配置文件名的占位符后,就开始refresh容器 @Override public void refresh() throws BeansException, IllegalSt ...

随机推荐

  1. POJ1088滑雪(记忆化搜索)

    就是用DP,DP[i][j]是在这个(i,j)位置作为起点的最长长度. 因为可能会超时,DP的话每次就是记录,然后就不用回溯了. 很简单的DFS里面的记忆化搜索. #include <stdio ...

  2. hyperledger fabric 1.0.5 分布式部署 (一)

    环境是个人虚拟机ubuntu 16.04 64 位版本 前期用户需要先安装好:gcc.g++.git 软件 安装 golang 首先给环境安装一个 go 语言环境,版本最好在1.8 以上 golang ...

  3. C# 面向对象之3个基本特征

    C#是面向对象的语言,每个面向对象语言都有3个基本特征: *封装----把客观的事物封装成类,并将类的内部实现隐藏,以保证数据的完整性. *继承----通过继承可以复用父类的代码. *多态----允许 ...

  4. [BZOJ2251/BJWC2010]外星联络

    Description 小 P 在看过电影<超时空接触>(Contact)之后被深深的打动,决心致力于寻找外星人的事业.于是,他每天晚上都爬在屋顶上试图用自己的收音机收听外星人发来的信息. ...

  5. GYM 101673G(dp)

    dp[i][j][0/1]:第i天处于第j状态要不要吃. const int maxn = 1e2 + 5; int n, a[maxn], b[maxn]; int dp[maxn][maxn][2 ...

  6. SSAS中雪花模型

    上面的[销售事实表]与[门店]维度.[集团]维度就组成了一个雪花模型. 1.可以把[集团]关联到[门店]的维度上去: 2.如果要把[集团]作为一个单独的维度,先在[维度]里把Dim_Group添加进来 ...

  7. java中的线程安全是什么?什么叫线程安全?什么叫不安全?

    java中的线程安全是什么: 就是线程同步的意思,就是当一个程序对一个线程安全的方法或者语句进行访问的时候,其他的不能再对他进行操作了,必须等到这次访问结束以后才能对这个线程安全的方法进行访问 什么叫 ...

  8. Java环境安装与Eclipse安装

    1.jdk下载安装 2.Eclipse下载安装 遇到的问题: 出现问题原因可能有两个:1)没有配置环境变量 2)jdk和eclipse安装的版本不一致,都是64位或者都是32位. 本人出现错误的原因: ...

  9. 重新安装Magento CE 2.1.0

    删除 var/cache 文件夹 删除 var/generation文件夹 删除 app/etc/config.php 删除 app/etc/env.php 如果您觉得阅读本文对您有帮助,欢迎转载本文 ...

  10. DSO的接口文档[转]

    本文从别处转来: (开发环境)使用前先注册一下DSOFramer.ocx 操作:将DSOFramer.ocx复制到C:\windows\system32目录下, 开始->运行->regsv ...