您的位置:首页 > 编程语言 > Java开发

使用注解,实现ssh项目中spring配置文件的零配置,约定优于配置

2011-07-14 18:13 876 查看
最开始使用spring整合ssh框架开发项目的时候,需要用spring来管理bean,所以就需要写很多的配置文件配置bean,需要配置bean中的property。刚刚学到了一个方法可以极大程度的降低写配置文件的复杂度,使用注解来代替配置文件。

1.在需要声明的bean上添加@Component之类的注释,可以用@Component("string"),来表明要将这个bean声明成的名称,默认是将类的首字母小写,其余不变
@Component:标注一个普通的Spring bean类
@Controller:标注一个控制器组件类
@Service:标注一个业务逻辑组件类
@Repository:标注一个DAO组件类
2.在spring配置文件中,如applicationContext.xml文件中,在beans写入如下代码

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.softeye.group"></context:component-scan>
</beans>
不要忘了
xmlns:context="http://www.springframework.org/schema/context"


http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"

的声明。

<context:component-scan base-package="com.softeye.group"></context:component-scan>
说明在com.softeye.group包下面进行bean的搜索。

3.在一个bean需要依赖其他bean的时候,用@Resource来表明,相当于配置文件中的property、ref

@Resource有个name属性,@Resource(name="......"),表明要被注入的bean实例的名称。
@Resource 可以用在set方法上,也可以直接用在域Field上,用在域上的时候可以连get set方法都省略,非常的方便。

4.spring的注解还有如@DependsOn,@Lazy等等,需要更深的研究。

5.在spring整合hibernate时,如果使用HibernateDaoSupport,需要在配置文件中声明property ref属性声明sessionFactory,不能用注解来进行,HibernateDaoSupport中的setSessionFactory方法是final的,继承使用这个类还必须使用sessionFactory这个bean,所以此时在配置文件中进行声明是最好的方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: