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

最开始使用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,所以此时在配置文件中进行声明是最好的方法。


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值