首先查看 @Autowired為何
@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;
}
tp-link通過源碼我們知道他是spring的一個注解接口,有一個方法
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.有注解存在
@Autowired
UserService userService;
3.有對應的setter方法
public void setUserService(UserService userService) {
this.userService = userService;
}
4.如果是接口或者抽象類的話那么需要實現類唯一,否則創建實例出錯
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認識
@Service
public class UserServiceImpl implements UserService {
。。。。。。。
}
綜上可得spring只管理他認識的bean,有2中方式讓spring知道bean的存在
1.注解方式
2.bean配置
posted on 2011-06-17 11:23
墻頭草 閱讀(2737)
評論(0) 編輯 收藏