spring注解(二)

来源:互联网 发布:美工专业培训学校 编辑:程序博客网 时间:2024/05/16 18:14

一、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;@Controllerpublic 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;@Servicepublic 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;@Overridepublic void save() {System.out.println("userRepository的实现类,save方法");    System.out.println("testObject");}}

实现类二:UserJdbcRepository.java

@Repositorypublic class UserJdbcRepository implements UserRepository{@Overridepublic void save(){    System.out.println("UserJdbcRepository.....save");}}

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

@Servicepublic 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”)

@Servicepublic class UserService {    @Autowired    @Qualifier("userRepositoryImpl")    private UserRepository userRepository;public void add(){    System.out.println("UserSerivce add......");}}

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

0 0