现在的位置: 首页 > 综合 > 正文

Spring的Annotation配置

2018年04月07日 ⁄ 综合 ⁄ 共 1626字 ⁄ 字号 评论关闭

可以在-hibernate.xml配置文件中设置使用SpringAnnotation的配置。

<beansxmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"

    xmlns:context="http://www.springframework.org/schema/context"

    xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd

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

 

 

加入下面的配置,设置允许使用Annotation,并设置Annotation作用的包范围,其中要包括dao.impl,service.impl和action。

<context:annotation-config></context:annotation-config>

    <context:component-scan     base-package="org.liky.ssh.back.action,org.liky.ssh.back.service.     impl,org.liky.ssh.dao.impl">

</context:component-scan>

 

此时可以将-dao,-service,-struts三个配置文件删除。

 

 

打开DAOImpl文件,加入以下Annotation配置。

// 表示该类自动配置成为一个Spring<bean>,id为类名首字母小写

@Component

public
class
NewsDAOImpl extends HibernateDaoSupportimplements INewsDAO {

    // 自动将hibernateTemplate通过构造方法注入到DAOimpl.

    @Autowired

    publicNewsDAOImpl(HibernateTemplate hibernateTemplate) {

       super.setHibernateTemplate(hibernateTemplate);

    }

 

 

同时,Service中也要修改这个内容

@Service

public
class
NewsServiceImplimplements INewsService {

    privateINewsDAOnewsdao;

//将newsDAOImpl注入到DAOServiceImpl

    @Resource(name="newsDAOImpl")

    public
void
setNewsdao(INewsDAO newsdao) {

       this.newsdao =newsdao;

    }

}

 

 

在Action中配置

// 也表示是一个<bean>

@Controller

// 不使用单例设计

@Scope(value=
"prototype"
)

public
class
NewsActionextends ActionSupport {

    @Resource(name=
"newsServiceImpl"
)

    public
void
setService(INewsService service) {

       this.service =service;

    }

}

抱歉!评论已关闭.