spring注解(二)

一、bean之间有关联关系

因此,只是一个是不行的,还是最好用到@Autowired。如下面的代码,用@Autowired注解的bean必须是已经被配置了的,如果没有被配置那么会报异常。如下面代码中,用@Autowired注解了一个UserSerivice,这样在UserService类中一定要@Component注解。
代码段一:在UserController中用到了UserService类

package com.spring.annotation.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.spring.annotation.service.UserService;
@Controller
public class UserController {
    @Autowired
    private UserService userService;

public void execute(){
    System.out.println("UserController execute......");
}
}

代码段二:UserService被注解了@Service。

package com.spring.annotation.service;

import org.springframework.stereotype.Service;

@Service
public class UserService {
public void add(){
    System.out.println("UserSerivce add......");
}
}

如果上面代码中,没有注解@Service的话会报异常。
注意有一种方法可以让我们不用@component等来注解就可以自动注入bean
看上面的代码如果没有@Service注解那个UserService类,也可以用@Autowired来加入bean,那就是设置required属性为true。写成@Autowired(required=true)。

二、当出现两个类实现同一接口的情况下应该是指注入哪个?

接口代码:UserRepository.java

package com.spring.annotation.repository;
public interface UserRepository {
void save();
}

实现类一:UserRepositoryImpl.java

@Repository("userRepository")
public class UserRepositoryImpl implements UserRepository{
    @Autowired(required=false)
    private TestObject testobject;
@Override
public void save() {
System.out.println("userRepository的实现类,save方法");    
System.out.println("testObject");
}
}

实现类二:UserJdbcRepository.java

@Repository
public class UserJdbcRepository implements UserRepository{
@Override
public void save(){
    System.out.println("UserJdbcRepository.....save");
}
}

下面代码注入了这个接口的bean,到底指的是哪个呢?

@Service
public class UserService {

    private UserRepository userRepository;
    @Autowired
    public void setUserRespository(UserRepository userRepository ){
        this.userRepository=userRepository;
    }
public void add(){
    System.out.println("UserSerivce add......");
}
}

如下面的代码,注入的是一个实现类UserRepositoryImpl,,因为人家有注明@Repository(“userRepository”)。所以用的是这个。如果去掉就会报错,因为程序不知道去找哪个实现类。这种有两个实现类的有两种解决方案:
(1)像上面这样,在实现类上注明的名字刚好和属性名一样
(2)另一种方式是在注入的时候标明
@Autowired
@Qualifier(“userRepositoryImpl”)

@Service
public class UserService {
    @Autowired
    @Qualifier("userRepositoryImpl")
    private UserRepository userRepository;

public void add(){
    System.out.println("UserSerivce add......");
}
}

其实还可以有@Resource和@Inject来注解,但是这个和@Autowired功能一样,所以就不用管了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值