Spring 4.0.2 学习笔记(2) - 自动注入及properties文件的使用

时间:2021-06-14 03:48:44

上一篇继续, 学习了基本的注入使用后,可能有人会跟我一样觉得有点不爽,Programmer的每个Field,至少要有一个setter,这样spring配置文件中才能用<property>...</property>来注入. 能否不要这些setter方法? 答案是Yes

一、为Spring配置文件,添加annotation支持,以及 default-autowire属性

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"
default-autowire="byName"> <context:annotation-config/> <bean id="jimmy" class="com.cnblogs.yjmyzz.domain.Programmer"/> <bean id="computerlist" class="java.util.ArrayList">
<constructor-arg>
<list>
<bean class="com.cnblogs.yjmyzz.domain.MacBook"/>
<bean id="t60" class="com.cnblogs.yjmyzz.domain.ThinkPad"/>
</list>
</constructor-arg>
</bean> <bean id="wangcai" class="com.cnblogs.yjmyzz.domain.Dog"/> <bean id="jimmy_name" class="java.lang.String">
<constructor-arg>
<value>jimmy.yang</value>
</constructor-arg>
</bean> </beans>

注: 相对原来的版本,有几个小变化:

a) 最开始的xml声明部分,添加了xmlns:context

b) default-autowired设置为byName,运行时,将通过配置文件中,bean的id/name,来实现自动注入(后面会有代码演示)

c) 添加了<context:annotation-config/> ,这表明Spring允许在java类中,可以通过在field成员上,通过注解自动注入,而不再需要在配置文件中,手动指定property注入

d) 名为jimmy的bean,去掉<property>...</property>的注入配置

那么,问题来了,运行时,jimmy如何得到name,pet,computers这些属性的实例呢?

二、使用@Resource自动注入

Spring支持好几种注解自动注入,比如@Inject,@Resource,@Autowired,这里只演示@Resource这一种

package com.cnblogs.yjmyzz.domain;
import javax.annotation.Resource; import java.util.List;
public class Programmer { @Resource(name = "jimmy_name")
private String name; @Resource(name = "wangcai")
private Pet pet; @Resource(name = "computerlist")
private List<Computer> computers; public void show() {
System.out.print("My name is " + name);
System.out.print(", and I have " + computers.size() + " computer" + (computers.size() > 1 ? "s" : "") + ":");
System.out.println();
for (Computer c : computers) {
c.showInfo();
}
System.out.println("And I have a pet, everyday,when I go home, it will welcome me by ");
pet.welcomeMeToHome(); }
}

对比原来的版本,去掉了所有的setter,整个类看上去非常清爽,@Resouce后的name=XXX,这里的XXX要跟Spring配置文件中,bean的id一致

未完待续...

属性文件的使用,明天有空再来补上