zoukankan      html  css  js  c++  java
  • 06Spring_使用注解配置bean对象

    Spring注解开发需要jar包 和 xml开发 一样的 !

    第一步: 新建项目, 导入jar包(就是前一篇文章里面的那几个核心jar包)

    第二步: 在需要spring创建对象类上面 添加@Component (注解 来自spring2.5 )

    第三部:修改applicationContext.xml。

    <?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:aop="http://www.springframework.org/schema/aop"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:context="http://www.springframework.org/schema/context"
           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/context 
                               http://www.springframework.org/schema/context/spring-context-2.5.xsd
                               http://www.springframework.org/schema/tx 
                               http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
         <context:component-scan base-package="cn.itcast.spring.quickstart"></context:component-scan>
            
    </beans>
       <context:component-scan base-package="cn.itcast.spring.quickstart"></context:component-scan>这一步很关键,这么一配置的话,
    程序就会从base-package="cn.itcast.spring.quickstart"这个包下面的文件里面去寻找被注解过的类。不然怎么找的到。


    JUnit测试代码:
    public class quiclkstatrtytest {
        @Test
        public void testDemo1()
        {
            ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
            UserService userService=applicationContext.getBean("userService",UserService.class);
        System.out.print(userService);    
            
        }
    
    }
    
    

    Spring为了细分组件的功能,在提供@Component注解,提供三个等价的注解

           @Controller 控制器,表示web层组件  ---- action

           @Service 业务类,表示业务层组件 --- service

           @Repository 表示持久层的组件 --- dao

    已经有了@Component了为什么还要有上面三个注解呢?因为Spring 公司要考虑到以后的升级,为单独的注解添加不同的特别功能。现在的话这三个注解和@Component注解还是没有区别的,
    用哪个都是一样的。但是为了代码更加规范还是建议根据不同的环境,采用上面的注解。



  • 相关阅读:
    高级程序员应该具备什么能力
    二 八 定 律
    二八定律全面分析
    Java 网络爬虫获取网页源代码原理及实现
    vijosP1371 方程的解
    vijosP1413 Valentine’s Present
    vijosP1289 老板娘的促销方案
    vijosP1092 全排列
    vijosP1049 送给圣诞夜的礼品
    vijosP1210 盒子与球
  • 原文地址:https://www.cnblogs.com/shenxiaoquan/p/5707122.html
Copyright © 2011-2022 走看看