注解模式2(自动注入和多个实现接口的子类的用法)
1、配置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:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:c="http://www.springframework.org/schema/c" xmlns:cache="http://www.springframework.org/schema/cache" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd"> <context:component-scan base-package="com.wh"></context:component-scan> </beans>
2、编写接口
package com.wh.zhujie;
import org.springframework.stereotype.Repository;
@Repository
public interface IDao {
String info();
}
3、编写实现接口的不同子类
package com.wh.zhujie;
import org.springframework.stereotype.Repository;
@Repository
public class MySqlDaoImpl implements IDao {
@Override
public String info() {
return "mySqlDaoImpl";
}
}
package com.wh.zhujie;
import org.springframework.stereotype.Repository;
@Repository
public class OracleDaoImpl implements IDao {
@Override
public String info() {
return "OracleDaoImpl";
}
}
4、编写service层的类
package com.wh.zhujie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
/**
* @Resource(name="mySqlDaoImpl") 手动注入
* @Autowire 自动注入
*
* 若出现一个接口对应多个不同的子类实现时,可以通过
* @Qualifier(value="oracleDaoImpl")
* 来确定使用哪个子类实现
*/
@Service
public class UserService {
@Autowired
@Qualifier(value="oracleDaoImpl")
private IDao dao;
public String info() {
return dao.info();
}
public IDao getDao() {
return dao;
}
public void setDao(IDao dao) {
this.dao = dao;
}
}
5、编写测试类
package com.wh.zhujie;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestMVC {
public static void main(String[] args) {
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
UserService us=(UserService)ac.getBean("userService");
System.out.println(us.info());
}
/**
* 运行结果:
* OracleDaoImpl
*/
}

浙公网安备 33010602011771号