commons-logging 和log4j包下载 Spring根据XML配置文件生成对象
需要用到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配置文件生成对象的更多相关文章
- Spring根据XML配置文件注入对象类型属性
这里有dao.service和Servlet三个地方 通过配过文件xml生成对象,并注入对象类型的属性,降低耦合 dao文件代码: package com.swift; public class Da ...
- Spring根据XML配置文件注入属性 其实也是造bean,看看是使用constructor还是setter顺带完成属性赋值
方法一使用setter方法 package com.swift; public class Book { private String bookName; public void setBook(St ...
- Spring 通过XML配置文件以及通过注解形式来AOP 来实现前置,环绕,异常通知,返回后通知,后通知
本节主要内容: 一.Spring 通过XML配置文件形式来AOP 来实现前置,环绕,异常通知 1. Spring AOP 前置通知 XML配置使用案例 2. Spring AOP ...
- JavaWeb_(Spring框架)xml配置文件
系列博文 JavaWeb_(Spring框架)xml配置文件 传送门 JavaWeb_(Spring框架)注解配置 传送门 Xml配置 a)Bean元素:交由Spring管理的对象都要配置在bean ...
- [error] eclipse编写spring等xml配置文件时只有部分提示,tx无提示
eclipse编写spring等xml配置文件时只有<bean>.<context>等有提示,其他标签都没有提示 这时就需要做以下两步操作(下面以事务管理标签为例) 1,添加命 ...
- Spring框架xml配置文件 复杂类型属性注入——数组 list map properties DI dependency injection 依赖注入——属性值的注入依赖于建立的对象(堆空间)
Person类中的各种属性写法如下: package com.swift.person; import java.util.Arrays; import java.util.List; import ...
- 如何配置多个Spring的xml配置文件(多模块配置)
如何使用多个Spring的xml配置文件(多模块配置) (2009-08-22 13:42:43) 如何使用多个Spring的xml配置文件(多模块配置) 在用Struts Spring Hibe ...
- Spring 在 xml配置文件 或 annotation 注解中 运用Spring EL表达式
Spring EL 一:在Spring xml 配置文件中运用 Spring EL Spring EL 采用 #{Sp Expression Language} 即 #{spring表达式} ...
- spring读取xml配置文件(二)
一.当spring解析完配置文件名的占位符后,就开始refresh容器 @Override public void refresh() throws BeansException, IllegalSt ...
随机推荐
- 【NOI省选模拟】小奇的花园
「题目背景」 小奇在家中的花园漫步时,总是会思考一些奇怪的问题. 「问题描述」 小奇的花园有n个温室,标号为1到n,温室以及以及温室间的双向道路形成一棵树. 每个温室都种植着一种花,随着季节的变换,温 ...
- 【SpringCloud构建微服务系列】分布式链路跟踪Spring Cloud Sleuth
一.背景 随着业务的发展,系统规模越来越大,各微服务直接的调用关系也变得越来越复杂.通常一个由客户端发起的请求在后端系统中会经过多个不同的微服务调用协同产生最后的请求结果,几乎每一个前端请求都会形成一 ...
- JIRA中的标记语言的语法参考
前言 看到网上有的文章说JIRA是使用Textile这门标记语言,有些语法和Wikitext和Markdown相像.JIRA在2017年进行了一次大更新,某些语法可能和以前不大一样,这里纪录一下常用的 ...
- python操作redis之hash操作
# __author__ = 'STEVEN' import redis,time #连接池 polls = redis.ConnectionPool(host='192.168.43.22',por ...
- python异常之EOFError: Ran out of input
出现该问题一般是由于你在以写模式打开文件后未关闭的情况下又去以读模式操作该文件时报的错误 # coding = utf-8 import pickle #定义一个boy类 class boy(): d ...
- 网络请求方法(SDK封装可以替换afn)
//个人觉得 sdk开发时候 最好不要用第三方 最好可以用最原始的方法 替换 此处仅做sdk封装使用 留存+(void)GET:(NSString *)urlStr params:(NSDiction ...
- Longest Palindromic Substring笔记
这是一道在leetcode上看到的题目 一开始,我能想到的思路是蛮力法: 就遍历每个字符,然后对每个字符都尝试从1到n的长度,看有没有回文串,并记录以该字符起始的回文串的最大长度.这个思路其实没有上手 ...
- awk一些简单命令
最简单地说, AWK 是一种用于处理文本的编程语言工具.AWK 在很多方面类似于 shell 编程语言,尽管 AWK 具有完全属于其本身的语法. 尽管操作可能会很复杂,但命令的语法始终是: awk ' ...
- 访问NopCommerce的Admin 运行Nop.Admin后台管理
Step 1.下载和安装NopCommerce的源码: Step 2.打开和运行Presentation下的Nop.Web 项目: Step 3.初次运行 会弹出界面 配置管理员账号 和 数据库信息: ...
- aspectj xml
1.接口和类 1.1 ISomeService 接口 public interface ISomeService { public void doSome(); public void dade(); ...