S2SH注解配置终极攻略由刀豆文库小编整理,希望给你工作、学习、生活带来方便”。
0配置,SSH全注解
全注解帮我们省去了大量的配置文件,但是必要的配置还是不可少的 spring.xml配置文件中需要配置:
入)
(告诉spring容器扫描com下的包,(声明使用注解对使用注解的bean进行管理)的事务)
spring.xml完整代码:
xmlns:xsi=“http://www.daodoc.com/2001/XMLSchema-instance”
xmlns:aop=“http://www.daodoc.com/schema/aop”
xmlns:context=“http://www.daodoc.com/schema/context”
xmlns:tx=“http://www.daodoc.com/schema/tx”
xsi:schemaLocation=“http://www.daodoc.com/schema/beans
http://www.daodoc.com/schema/beans/spring-beans-2.5.xsdhttp://www.daodoc.com/schema/tx
http://www.daodoc.com/schema/tx/spring-tx-2.5.xsd
http://www.daodoc.com/schema/aop
http://www.daodoc.com/schema/aop/spring-aop-2.5.xsd
http://www.daodoc.com/schema/context
http://www.daodoc.com/schema/context/spring-context-2.5.xsd”>
(声明用注解进行依赖注
cla=“org.springframework.jdbc.datasource.DriverManagerDataSource”>
value=“com.mysql.jdbc.Driver”>
cla=“org.springframework.orm.hibernate3.annotation.AnnotationSeionFactoryBean”>
org.hibernate.dialect.MySQLDialect
true
com.bmh.po.League
com.bmh.po.Team
com.bmh.po.ChampionShip
com.bmh.po.Group
cla=“org.springframework.orm.hibernate3.HibernateTemplate”>
cla=“org.springframework.orm.hibernate3.HibernateTransactionManager”>
需要注意的是:
seionFactory中没用mappingResources这个属性了,取而代之的是annotatedClaes,seionFactory对应的cla变了,这里需要的是支持注解的类 因为实体bean同样使用了注解,不再需要映射文件了
2.struts.xml配置文件中的package标签中的配置也都不用了,struts.xml中基本可以不用写什么
3.web.xml不变
4.action层的类:BmhAction的注解
@Controller(“bmhAction”)//声明是控制层的组件,名为bmhAction,不指定的话默认是类的简单名的第一个字母小写
@Namespace(“/”)//声明命名空间,相当于struts.xml中
@Results({//如果return的字符串为“test”则转到testDirection.jsp
@Result(name=“test”,location=“/WEB-INF/test/testDirection.jsp”),@Result(name=“error”,location=“/WEB-INF/test/error.jsp”)
})
@ExceptionMappings({//如果方法中出现该异常则返回“error”,error根据上面的配置,让浏览器跳转
@ExceptionMapping(exception = “java.lang.Exception”,result=“error”)})
//这里要继承ActionSupport,不然可能出现找不到action的错误
public cla BmhAction extends ActionSupport{
@Resource(name = “bmhService”)//依赖注入,默认按名称装配,如果没有匹配的才按类型装配,//这里我直接指明name=,就只能按名称装配了
private IBmhService bs;
5.service层的类:BmhService的注解
@Service(“bmhService”)//声明是业务层的组件
@Transactional//对类中所有方法采用默认的事务管理
public cla BmhService implements IBmhService {
@Resource(name = “bmhDao”)
private IBmhDao bd;
//也可以写着某些方法上
@Transactional(propagation=Propagation.REQUIRED)
public void testTx(){
bd.testTx1();
bd.testTx2();
}
6.DAO层的类:BmhDao的注解:
@Repository(“bmhDao”)
public cla BmhDao implements IBmhDao {
@Resource(name = “hibernateTemplate”)
private HibernateTemplate ht;
7.最后,还要对实体类进行注解:
@Entity//声明式实体类
@Table(name=“groupinfo”)//声明对应的表
public cla Group {
@Id//该属性对应的字段为主键
@GeneratedValue(generator=“group”)//采用名为group的生成策略@GenericGenerator(name=“group”,strategy=“native”)//主键生成策略@Column(name=“groupid”)//数据库中对应的字段名
private int groupId;
@Column(name=“groupname”)//普通的字段
private String groupName;
注意,上面的@Entity和@Table注解导入的是javax包下的类而不是hibernate的