<?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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config />
<!--这个配置藏式注册了多个对注释进行解析处理的处理器 -->
<bean id="personDaoBean"
class="eleven.spring.service.impl.PersonDaoBean">
</bean>
<bean id="personService"
class="eleven.spring.service.impl.PersonServiceBean">
</bean>
</beans>
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
package eleven.spring.service;
public interface PersonDao {
public abstract void add();
}
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
package eleven.spring.service;
public interface PersonService {
//面向接口编程,降低耦合度
public abstract void savePerson();
public abstract PersonDao getPersonDaoBean();
}
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
package eleven.spring.service.impl;
import eleven.spring.service.PersonDao;
public class PersonDaoBean implements PersonDao {
public PersonDaoBean() {
System.out.println("我是包seven.spring.service.impl类PersonDaoBean构造方法");
}
public void add() {
System.out.println("我是包seven.spring.service.impl类PersonDaoBean方法add");
}
}
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
package eleven.spring.service.impl;
import org.apache.log4j.Logger;
import javax.annotation.Resource;
import eleven.spring.service.PersonDao;
import eleven.spring.service.PersonService;
public class PersonServiceBean implements PersonService {
// 通过@Resource 和 @Autowirte 进行注释解析
// 的方式进行解析
// @Autowirte 按照类型
// @Resource 按照名称装配 若失败 再按照类型匹配
// 一但指定name属性,只能按照类型匹配
@Resource
private PersonDao personDaoBean;
private static Logger myLogger = Logger.getLogger(PersonServiceBean.class);
private String name;
private Integer id;
public void savePerson() {
myLogger.debug("我是包[seven.spring.service.impl]的类[PersonService]的[savePerson]方法");
myLogger.info(this.name);
this.personDaoBean.add();
}
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
package eleven.spring;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import eleven.spring.service.PersonService;
public class SpringTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void instanceSpring() {
// 在类路径下,寻找配置文件,实例化spring容器。
ApplicationContext ctx = new ClassPathXmlApplicationContext("/eleven/elevenbeans.xml");
//配置文件中bean的id,推荐首字母小写
PersonService personService = (PersonService)ctx.getBean("personService");
personService.savePerson();
}
}
先按照 成员变量的 名字(绿色) personDaoBean 进行注入
注入 失败的话 则根据 成员变量的 类型(亮兰色) 进行注入