Java代碼
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD})
public @interface Autowired {
/**
* Declares whether the annotated dependency is required.
* <p>Defaults to <code>true</code>.
*/
boolean required() default true;
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD})
public @interface Autowired {
/**
* Declares whether the annotated dependency is required.
* <p>Defaults to <code>true</code>.
*/
boolean required() default true;
} 通過源碼我們知道他是spring的一個註解接口,有一個方法
Java代碼
boolean required() default true;
boolean required() default true;
使用的時候必須滿足如下條件:
1.spring的配置文件必須加入能夠識別註解的東東
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
或者使用xml標註如下(註意版本)
xmlns:context
<context:component-scan base-package=”org.javaeye.*”/>
支持4種註解分別為@Component, @Serivce, @Controller, @Repository
@Controller:控制層
@Serivce:業務邏輯層
@Repository:持久層
2.有註解存在
Java代碼
@Autowired
UserService userService;
@Autowired
UserService userService; 3.有對應的setter方法
Java代碼
public void setUserService(UserService userService) {
this.userService = userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
} 4.如果是接口或者抽象類的話那麼需要實現類唯一,否則創建實例出錯
Java代碼
org.springframework.beans.factory.NoSuchBeanDefinitionException:
No unique bean of type
[com.sohu.suc.splatform.service.UserService] is defined:
expected single matching bean but found 2:
[userServiceHibernateImpl, userServiceImp]
org.springframework.beans.factory.NoSuchBeanDefinitionException:
No unique bean of type
[com.sohu.suc.splatform.service.UserService] is defined:
expected single matching bean but found 2:
[userServiceHibernateImpl, userServiceImp]
5.接口的實現必須讓spring認識,以bean的方式配置或者加註解讓spring認識
Java代碼
@Service
public class UserServiceImpl implements UserService {
。。。。。。。
}
@Service
public class UserServiceImpl implements UserService {
。。。。。。。
} 綜上可得spring隻管理他認識的bean,有2中方式讓spring知道bean的存在
1.註解方式
2.bean配置