如何用注解简化SSH框架

如何用注解简化SSH框架

一、简化代码第一步,删除映射文件,给实体类加上注解

@Entity //声明当前类为hibernate映射到数据库中的实体类

@Table(name="news") //声明table的名称

public class News {

@Id //声明此列为主键,作为映射对象的标识符

/**

* @GeneratedValue注解来定义生成策略

* GenerationType.TABLES 当前主键的值单独保存到一个数据库的表中

* GenerationType.SEQUENCE 利用底层数据库提供的序列生成标识符

* GenerationType.IDENTITY 采取数据库的自增策略

* GenerationType.AUTO 根据不同数据库自动选择合适的id生成方案,这里使用mysql,为递增型

*/

@GeneratedValue(strategy = GenerationType.AUTO)

private Integer id;

@Column(name="title",nullable=false)

private String title;

@Column(name="content",nullable=false)

private String content;

@Column(name="begintime",nullable=false)

private Date begintime;

@Column(name="username",nullable=false)

private String username;

public News() {

super();

}

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getTitle() {

return title;

}

public void setTitle(String title) {

this.title = title;

}

public String getContent() {

return content;

}

public void setContent(String content) {

this.content = content;

}

public Date getBegintime() {

return begintime;

}

public void setBegintime(Date begintime) {

this.begintime = begintime;

}

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

}

修改applicationContext.xml文件

news.entity

二、用注解代替注入:

1.其实,注解本身做不了任何事情,和XML一样,只起到配置的作用,主要在于背后强大的处理器,其中就包括了配置项里面的注解所使用的处理器,所以配置了之后,便无需再配置

2.@Autowired

在java代码中使用@Autowired或@Resource注解方式进行装配 ,这两个注解的区别是:@Autowired默认按类型装配,@Resource默认按名称装配,当找不到名称匹配的bean才会按类型装配。@Autowired一般装配在set方法之上,也可以装配在属性上边。

@Autowired是根据类型进行自动装配的。如果当Spring上下文中存在不止一个所要装配类型的bean时,就会抛出BeanCreationException异常;我们可以使用@Qualifier配合@Autowired来解决这些问题。

3.@Resource

@Resource的作用相当于@Autowired

@Resource有两个属性是比较重要的,分别是name和type,Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。所以如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既不指定name也不指定type属性,这时将通过反射机制使用byName自动注入策略

4.使用Spring注解完成Bean的定义以上我们介绍了通过@Autowired或@Resource来实现在Bean中自动注入的功能,下面我们将介绍如何注解Bean,从而从XML配置文件中完全移除Bean定义的配置。@Component:只需要在对应的类上加上一个@Component注解,就将该类定义为一个Bean了:

使用@Component注解定义的Bean,默认的名称(id)是小写开头的非限定类名。如这里定义的Bean名称就是userDaoImpl。你也可以指定Bean的名称:@Component("userDao")@Component是所有受Spring管理组件的通用形式,Spring还提供了更加细化的注解形式:

@Repository、@Service、@Controller,它们分别对应存储层Bean,业务层Bean,和展示层Bean。目前版本)中,这些注解与@Component的语义是一样的,完全通用,在Spring以后的版本中可能会给它们追加更多的语义。所以,我们推荐使用@Repository、@Service、@Controller来替代@Component。

三、使用让Bean定义注解工作起来

相关文章