@martin0207
2018-04-20T12:09:53.000000Z
字数 2103
阅读 816
Java学习
Spring是Java开发中,非常主流的开发框架。
Spring的Jar包下载教程
commons-logging下载地址
导入Spring的lib文件夹下所有Jar包和commons-logging的jar包
在src文件夹下,创建xml文件,通常使用beans.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">
<!-- 这里配置bean信息 -->
</beans>
创建一个‘HelloWorld’类,放在model包下
public class HelloWorld {
public String hello() {
return "hello world";
}
}
<?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-4.1.xsd">
<!--
创建如下bean,等于完成了:
HelloWorld helloworld = new HelloWorld();
-->
<!--
prototype:多例模式
singleton:单例模式(默认)
-->
<bean id="helloworld" class="model.HelloWorld" scope="prototype"/>
</beans>
以上内容,即配置Spring基本信息。
beans配置完成之后,我们实现了类之间的解耦。如果要使用配置中的对象,需要创建Spring工厂
// 创建Spring的工厂
private BeanFactory factory = new ClassPathXmlApplicationContext("beans.xml");
后续对象的获取,都会通过工厂来生产。
// 通过工厂获取Spring对象
// 此处的'helloworld'是beans.xml配置文件的id
// HelloWorld hWord = (HelloWorld) factory.getBean("helloworld");
HelloWord helloWord = factory.getBean("helloworld", HelloWorld.class);
// 这时hello对象就是被Spring管理的对象
System.out.println(helloWord.hello());
完整代码代码如下:
public class Test01 {
// 创建Spring的工厂
private BeanFactory factory = new ClassPathXmlApplicationContext("beans.xml");
@Test
public void testHello() {
// 通过工厂获取Spring对象
// 此处的'helloworld'是beans.xml配置文件的id
// HelloWorld hWord = (HelloWorld) factory.getBean("helloworld");
HelloWorld helloWord = factory.getBean("helloworld", HelloWorld.class);
// 这时hello对象就是被Spring管理的对象
System.out.println(helloWord.hello());
HelloWorld helloWord2 = factory.getBean("HelloWorld",HelloWorld.class);
//如果在beans配置中,没有做scope配置,默认是singleton(单例模式)
System.out.println(helloWord==helloWord2);
}
}
测试结果:
hello world
false
以上是我刚看完教程,记录下来的最简单配置,后面还会学习更多的功能使用。如果有不对,请告诉我,立马修改。谢谢