網頁

2018/8/30

Spring 使用@Autowired依賴注入物件

Spring的@Autowired用來依賴注入物件,典型的用法就是掛在類別成員變數上。@Autowired預設會依注入對象的類別型態來選擇容器中相符的物件來注入。


例如下面的EmployeeServiceImpl中使用@Autowired來注入employeeDao的實例。稱為field injection

public interface EmployeeDao { ... }

@Repository("employeeDaoImpl")
public class EmployeeDaoImpl implements EmployeeDao { ... }

@Service
public class EmployeeServiceImpl implements EmployeeService{
    
    @Autowired
    private EmployeeDao employeeDao; // inject EmployeeDaoImpl instance
    
}

除了在成員變數名稱上用@Autowired注入,也可以在建構子(constructor)或成員變數的setter方法上使用@Autowired來注入實例。

在constructor上使用@Autowired。稱為constructor injection。

@Service
public class EmployeeServiceImpl implements EmployeeService { 
    
    private final EmployeeDao employeeDao;
    
    @Autowired // constructor injection
    public EmployeeService(EmployeeDao employeeDao) {
        this.employeeDao = employeeDao;
    }
}

從Spring 4.3以後,如果bean只有一個建構子,則constructor injection可以省略@Autowired。引述官方文件如下:

As of Spring Framework 4.3, an @Autowired annotation on such a constructor is no longer necessary if the target bean only defines one constructor to begin with. However, if several constructors are available, at least one must be annotated to teach the container which one to use.


在setter方法上使用@Autowired稱為setter injection

@Service
public class EmployeeServiceImpl implements EmployeeService { 
    
    private final EmployeeDao employeeDao;
    
    @Autowired // setter injection
    public void setEmployeeDao(EmployeeDao employeeDao) {
        this.employeeDao = employeeDao;
    }
}

@Autowired有一個required屬性預設為true,當Spring容器內沒有適當的bean可以注入時,會拋出NoSuchBeanDefinitionException,因此不確定是否有適合的bean可注入時可以將require設為false。

@Service
public class EmployeeServiceImpl implements EmployeeService { 
    
    @Autowired(required = false)
    private EmployeeDao employeeDao; // employeeDao will be null if no suitable bean
    
}


沒有留言:

張貼留言