posts - 241,  comments - 116,  trackbacks - 0
首先查看 @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 墙头草 阅读(2714) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航:
 
人人游戏网 软件开发网 货运专家