需要用到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如下:

  1. package com.swift;
  2.  
  3. public class User {
  4. public void fun() {
  5. System.out.println("fun is ready.");
  6. }
  7. }

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

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

在src下建立applicationContext.xml

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

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

配置对象创建

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="
  5. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  6. <!-- IoC 控制反转 SpringSpring根据XML配置文件生成对象 -->
  7. <bean id="user" class="com.swift.User"></bean>
  8. </beans>

创建Servlet类观察结果

  1. package com.swift;
  2.  
  3. import java.io.IOException;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.annotation.WebServlet;
  6. import javax.servlet.http.HttpServlet;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpServletResponse;
  9.  
  10. import org.springframework.context.ApplicationContext;
  11. import org.springframework.context.support.ClassPathXmlApplicationContext;
  12.  
  13. @WebServlet("/test")
  14. public class TestIOC extends HttpServlet {
  15. private static final long serialVersionUID = 1L;
  16. public TestIOC() {
  17. super();
  18. }
  19. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  20. response.getWriter().append("Served at: ").append(request.getContextPath());
  21. @SuppressWarnings("resource")
  22. //就是下边这几句了
  23. ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
  24. User user=(User) context.getBean("user");
  25. String userInfo=user.fun();
  26. response.getWriter().println();
  27. response.getWriter().append(userInfo);
  28. }
  29.  
  30. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  31. doGet(request, response);
  32. }
  33.  
  34. }
  1. //就是下边这几句了
    ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");//解析xml
  2. User user=(User) context.getBean("user");//得到对象
  3. String userInfo=user.fun();//使用对象
  4. response.getWriter().append(userInfo);//服务器输出

  1. 注意,如果User类中写了有参构造,而找不到无参构造,则<bean id="user" class="com.swift.User"></bean>这种约束会失败,无法成功创建对象,所以要加上无参构造,代码如下
  1. package com.swift;
  2.  
  3. public class User {
  4. private String userName;
  5. public User(String s) {
  6. this.userName=s;
  7. }
  8. public User() {}
  9.  
  10. public String fun() {
  11. return "User's fun is ready.";
  12. }
  13. }

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

  1. package com.swift;
  2.  
  3. public class BeanFactoryUser {
  4. public static User getUser() {
  5. return new User();
  6. }
  7. }

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

这时xml配置文件增加

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

把静态方法也填上

Servlet类的代码如下:

  1. package com.swift;
  2.  
  3. import java.io.IOException;
  4.  
  5. import javax.servlet.ServletException;
  6. import javax.servlet.annotation.WebServlet;
  7. import javax.servlet.http.HttpServlet;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10.  
  11. import org.springframework.context.ApplicationContext;
  12. import org.springframework.context.support.ClassPathXmlApplicationContext;
  13.  
  14. @WebServlet("/test2")
  15. public class TestIOCServlet2 extends HttpServlet {
  16. private static final long serialVersionUID = 1L;
  17. public TestIOCServlet2() {
  18. super();
  19. }
  20. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  21. response.getWriter().append("Served at: ").append(request.getContextPath());
  22. ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
  23. User user=(User) context.getBean("beanFactory");
  24. String s=user.fun();
  25. response.getWriter().println(s);
  26. }
  27.  
  28. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  29. doGet(request, response);
  30. }
  31.  
  32. }

实例工厂的方法

  1. package com.swift;
  2.  
  3. public class FactoryInstance {
  4. public User fun() {
  5. return new User();
  6. }
  7. }

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

也是可以的

配置文件如下写法

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

Servlet类实现结果

  1. package com.swift;
  2.  
  3. import java.io.IOException;
  4.  
  5. import javax.servlet.ServletException;
  6. import javax.servlet.annotation.WebServlet;
  7. import javax.servlet.http.HttpServlet;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10.  
  11. import org.springframework.context.ApplicationContext;
  12. import org.springframework.context.support.ClassPathXmlApplicationContext;
  13.  
  14. @WebServlet("/test3")
  15. public class TestIOCServlet3 extends HttpServlet {
  16. private static final long serialVersionUID = 1L;
  17.  
  18. public TestIOCServlet3() {
  19. super();
  20. }
  21. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  22. response.getWriter().append("Served at: ").append(request.getContextPath());
  23. ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
  24. User user=(User) context.getBean("user2");
  25. String s=user.fun();
  26. response.getWriter().append(s);
  27. }
  28. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  29. doGet(request, response);
  30. }
  31.  
  32. }

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>

  1.  

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. std::thread 在DLLMain 中会发生死锁 std::thread cause deadlock in DLLMain

    注意不要再DLLMain中使用 std::thread 否则会发生死锁. 但是可以使用 _beginthreadex (此函数可以使用lambda) 或者直接使用windows的底层函数: Creat ...

  2. [Xcode 实际操作]七、文件与数据-(16)解析XML文档

    目录:[Swift]Xcode实际操作 本文将演示如何解析XML文档. 项目中已添加一份XML文档:worker.xml <?xml version="1.0" encodi ...

  3. assembly x86(nasm)画三角形等图形的实现

    参考了一位大佬的博客 https://blog.csdn.net/qq_40298054/article/details/84496944传送门 https://blog.csdn.net/qq_40 ...

  4. 网络装机pxe服务器的配置过程

    网络装机pxe服务器的配置过程 背景: 针对于Linux运维工作中遇到的需要大批量安装Linux系统的情况,通过网络装机的方式实现无人值守安装Linux操作系统,现需要配置一台pxe服务器用于pxe批 ...

  5. Execution failed for task ':app:lintVitalRelease'.

    解决方法:在build.gradle文件的android部分添加如下代码: lintOptions { checkReleaseBuilds false abortOnError false} 最后成 ...

  6. 1-26HashSet简介

    Set的特点 Set里面存储的元素不能重复,没有索引,存取顺序不一致. package com.monkey1024.set; import java.util.HashSet; /** * Set的 ...

  7. py3.5 telnet的实例(在远程机器上批量创建用户)

    import sysimport telnetlibimport time HOST = ["172.18.217.12","172.18.217.13"]#往 ...

  8. Spring Security – security none, filters none, access permitAll

    1.概述 Spring Security提供了几种将请求模式配置为不安全或允许所有访问的机制.取决于这些机制中的哪一种 - 这可能意味着根本不在该路径上运行安全过滤器链,或者运行过滤器链并允许访问 2 ...

  9. js实现屏幕自适应局部

    <!doctype html> <html> <head> <meta charset="utf-8"> <title> ...

  10. CSS3在hover下的几种效果

    CSS3在hover下的几种效果代码分享,CSS3在鼠标经过时的几种效果集锦 效果一:360°旋转 修改rotate(旋转度数) * { transition:All 0.4s ease-in-out ...