spring_note 注解注入属性
一、spring注释注入属性
package:com.spring.service
public class AccountService {
@Resource // 按类型匹配
@Resource(name="accountDAOImpl") // 到配置文件中查找对应id的类
@Autowired //自动装配
@Qualifier("accountDAOImpl") //根据autowired来自动装配 查找在配置文件中对应的id的类
private IAccountDAO dao;
public IAccountDAO getDao() {
return dao;
}
public void setDao(IAccountDAO dao) {
this.dao = dao;
}
}
package:com.spring.dao
public interface IAccountDAO {
void select();
}
package:com.spring.dao.impl
public class AccountDAOImpl mplements IAccountDAO{
public void select() {
System.out.println("select account ........");
}
}
applicationContext.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" 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="accountService" class="com.spring.dao.impl.AccountDAOImpl"></bean>
</beans>
package:com.spring.junit
public class AccountTest {
private AccountService service;
@Before
public void before(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
service = (AccountService) ctx.getBean("accountService");
}
@Test
public void testFooService(){
service.getDao().select();
}
@After
public void after(){
service = null;
}
}