Spring之构造注入与设值注入
来源:互联网 发布:淘宝推广培训学校 编辑:程序博客网 时间:2024/05/16 11:39
Spring之构造注入与设值注入
Spring学了好久了,但是一直没时间总结,总是断断续续的,这段时间打算重新做下Spring这方面的功课。
这几天闲着没事赶紧做做总结。Spring的核心就是控制反转和依赖注入,依赖注入又可以分成构造注入和设值注入,使用构造注入可以在构建对象的同时一并完成依赖关系的建立,在对象的关系比较多时为了避免使用构造注入时造成的代码量过多,我们可以考虑使用设值注入。但是设置注入不能保证数据在执行过程中不被更改设定,所以我们要是想让一些数据变成只读或者私有,使用构造注入会好一点。
不过貌似设值注入用的更多一点。
首先建一个Web工程,然后将Spring的依赖包添加进去,
然后把Spring的核心配置文件beans.xml添加到src文件夹下面,创建HelloWorld.java程序如下:
package com.spring.test;public class HelloWorld {private String message; public HelloWorld() {}public HelloWorld(String message) {super();this.message = message;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}}
然后在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-2.5.xsd"><bean id="helloWorld" class="com.spring.test.HelloWorld"><constructor-arg index="0"><value>I am ZDX</value></constructor-arg></bean></beans>
以上这种配置方式是构造注入,设值注入需要在beans.xml中这样设置:
<bean id="helloWorld" class="com.spring.test.HelloWorld"><property name="message"><value>I am ZDX</value></property></bean>
然后编写测试代码:
package com.spring.test;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class HelloWorldTest {@Testpublic void test() {ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");HelloWorld helloWorld=(HelloWorld) context.getBean("helloWorld");System.out.println(helloWorld.getMessage());}}
还没深入,大概写一下。。。。