spring注解 -----最简单的注解与自动装配例子

来源:互联网 发布:论文写作的意义 知乎 编辑:程序博客网 时间:2024/05/17 04:36

spring注解 —–最简单的注解与自动装配例子

环境:maven,jdk1.8,eclipse

完整代码:http://download.csdn.net/download/yhhyhhyhhyhh/9949614

1.Spring常用注解

与利用xml配置bean相比,使用注解步骤简单不少,实现自动扫描装配Bean

常用注解 用途 @Controller 定义控制层Bean,如Action @Service 定义业务层Bean @Repository 定义DAO层Bean @Component 定义Bean, 不好归类时使用. @Autowired 默认按类型匹配,自动装配(Srping提供的),可以写在成员属性上,或写在setter方法上 (与@Resource效果大部分类似)

2.spring xml文件中开启注解扫描:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:context="http://www.springframework.org/schema/context"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd">    <!-- spring开启扫描,扫描注解的包及其下属的包-->    <context:annotation-config />    <context:component-scan base-package="com.ct.rd.bg" />    <!-- 视图页面配置 -->    <bean       class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <property name="prefix" value="/WEB-INF/views/" />        <property name="suffix" value=".jsp" />    </bean></beans>

3.

在Dao实现中,可以这样写:

@Repository("managerDao")public class ManagerDaoImpl implements IManagerDao {    protected final Log log = LogFactory.getLog(getClass());    public void add() {        // TODO Auto-generated method stub        log.info("@Repository(\"managerDao\")");    }}

在Service实现中,可以这样写::

@Service("managerService")public class ManagerServiceImpl implements IManagerService {    protected final Log log = LogFactory.getLog(getClass());    // @Resource(name ="managerDao")//或者用这个    @Autowired    private ManagerDaoImpl dto;    public void insert() {        // TODO Auto-generated method stub        log.info("@Service(\"managerService\")");        dto.add();    }

在Controller中,可以这样写::

@Controllerpublic class ManagerController {    protected final Log log = LogFactory.getLog(getClass());    // @Resource(name ="managerService")//或者用这个    @Autowired    private ManagerServiceImpl dtoService;    @RequestMapping("/login")    public String login() {        dtoService.insert();        log.info("test");        return "index";    }}

3.验证

log4j日志打印:Controller调用Service,Service调用Dao

这里写图片描述

原创粉丝点击