Spring bean 注解方式注入

来源:互联网 发布:led显示屏软件下载 编辑:程序博客网 时间:2024/05/11 12:15

对于Spring bean 注解装配 目前已经有大量的文章包括文档,现总结一下。


1. 在applicationContext中引入命名空间 


       对于命名空间,可以在eclipse中安装Spring IDE 插件,打开配置文件,,选择design视图,可以很方便的添加删除命名空间。


xmlns:context="http://www.springframework.org/schema/context"    http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-2.5.xsd  

      2. 在applicationContext中添加

<context:component-scan base-package="写上你要扫描的包"/>

对于<context:annotation-config/> 配置可以看这个文章,annotation


  3. Annotation

@Controller

@Controller("Bean的名称")

定义控制层

 

@Service          

@Service("Bean的名称")  

定义业务层

在使用这个注解时,一定不要引错了,否则很难找到注入失败的原因。特别是项目引入webservice的框架时。

 

@Repository   

@Repository("Bean的名称")

定义DAO层

 

@Component  

定义一般的Bean


@Resource

是JSR-250规范中的。不建议使用。


@Autowired

可以标记没有get、set方法的私有字段

可以标记构造函数

可以标记普通的方法


对于这个注解,可以标记没有set、get方法的私有字段。

但是不能滥用,对于字段,如果对外是可获取或者可修改的,一定要有相应的set、get方法。

不能为了使用这个注解,而不去分析该不该有set、get方法。


@Autowired(required=true)  

如果Spring解析的时候,没有找到匹配的bean则抛出异常,默认为false



这篇文章写的比较详细,代码示例可以看这里,Spring bean 注解配置


原创粉丝点击