06Spring_使用注解配置bean对象

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注解还是没有区别的,
用哪个都是一样的。但是为了代码更加规范还是建议根据不同的环境,采用上面的注解。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值