首先查看 @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通過(guò)源碼我們知道他是spring的一個(gè)注解接口,有一個(gè)方法
boolean required() default true;
使用的時(shí)候必須滿(mǎn)足如下條件:
1.spring的配置文件必須加入能夠識(shí)別注解的東東
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
或者使用xml標(biāo)注如下(注意版本)
xmlns:context
<context:component-scan base-package="org.javaeye.*"/>
支持4種注解分別為@Component, @Serivce, @Controller, @Repository
@Controller:控制層
@Serivce:業(yè)務(wù)邏輯層
@Repository:持久層
2.有注解存在
@Autowired
UserService userService;
3.有對(duì)應(yīng)的setter方法
public void setUserService(UserService userService) {
this.userService = userService;
}
4.如果是接口或者抽象類(lèi)的話那么需要實(shí)現(xiàn)類(lèi)唯一,否則創(chuàng)建實(shí)例出錯(cuò)
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.接口的實(shí)現(xiàn)必須讓spring認(rèn)識(shí),以bean的方式配置或者加注解讓spring認(rèn)識(shí)
@Service
public class UserServiceImpl implements UserService {
。。。。。。。
}
綜上可得spring只管理他認(rèn)識(shí)的bean,有2中方式讓spring知道bean的存在
1.注解方式
2.bean配置
posted on 2011-06-17 11:23
墻頭草 閱讀(2737)
評(píng)論(0) 編輯 收藏