Spring基于属性注入提供的注解有AutoWired
,Qualifier
,Resource
,Value
AutoWired
根据属性类型自动装配
目标:将dao注入到service中
public interface Cup {
void constitute();
}
@Repository
public class CupImpl implements Cup{
@Override
public void constitute() {
System.out.println("make of glass");
}
}
@Service
public class CupService {
// 将Cup注入到Service中,基于类型注入
@Autowired
private Cup cup;
public void effect() {
cup.constitute();
System.out.println("装了一杯水");
}
}
测试
@Test
public void test1() {
ApplicationContext ac = new ClassPathXmlApplicationContext("xml路径");
CupService cupService = applicationContext.getBean("cupService", CupService.class);
cupService.effect();
}
//make of glass
//装了一杯水
Qualifier
根据属性名称注入,与AutoWired一起使用,主要是用于区分如果一个接口有多个实现类,依旧按照类型注入的话就找不到具体是哪一个
@Component(value = "heheheheh")
public class CupImpl implements Cup{
@Override
public void constitute() {
System.out.println("make of glass");
}
}
@Service
public class CupService {
@Autowired
// Qualifier与AutoWired一起使用,根据名称确定具体那个对象(如果一个接口有多个实现类)
@Qualifier(value = "heheheheh")
private Cup cup;
public void effect() {
cup.constitute();
System.out.println("装了一杯水");
}
}
Resource
可以根据类型注入,也可以根据名称注入
@Component // 根据类型注入
@Component(value="byName") // 使用名称进行注入
public class CupImpl implements Cup{
@Override
public void constitute() {
System.out.println("make of glass");
}
}
@Service
public class CupService {
@Resource // 使用类型进行注入
@Resource(value="byName") // 根据名称注入
private Cup cup;
public void effect() {
cup.constitute();
System.out.println("装了一杯水");
}
}
Value
注入普通属性
@Service
public class CupService {
// 将abc赋值给name,相当于xml中property标签作用
@Value(value="adb")
private String name;
public void effect() {
System.out.println(name);
}
}
补充
Resource是javax.annotation中的注解,AutoWired是Spring中的注解。建议使用AutoWired
全注解开发
1)使用配置类代替配置文件
@Configuration
@ComponentScan("扫描包路径")
public class MyConfig {
// 配置实体类中属性
@Bean
public User getUser(){
User user = new User();
user.setName("张三");
return user;
}
}
public interface UserDao {
void hello();
}
@Repository
public class UserDaoImpl implements UserDao{
@Override
public void hello() {
System.out.println("say hello");
}
}
@Service
public class UserServiceImpl {
// 注入属性
@Autowired
private UserDao userDao;
public void hello(){
userDao.hello();
}
}
// 测试类
@Test
public void test4(){
// 读取配置类
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(MyConfig.class);
// 获取使用@Service标注的类
UserServiceImpl userServiceImpl = ac.getBean("userServiceImpl", UserServiceImpl.class);
UserDaoImpl userDapImpl = ac.getBean("userDaoImpl", UserDaoImpl.class);
User user= ac.getBean("getUser", User.class);
userServiceImpl.hello();
user.getName();
userDapImpl.hello();
}
测试结果为:
say hello // serviceImpl 中输出
张三 // 在配置类中注入的属性
say hello // dao层输出