Spring的注解开发-Bean基本注解开发

Bean基本注解开发

  • Spring除了xml配置文件进行配置之外,还可以使用注解方式进行配置,注解方式慢慢成为xml配置的替代方案。我们有了xml开发的经验,学习注解开发就会方便很多,注解开发更加快捷方便。
  • Spring提供的注解有三个版本
    • 2.0时代,Spring开始出现注解
    • 2.5时代,Spring的bean配置可以使用注解完成
    • 3.0时代,Spring其它配置也可以通过注解完成,我们进入全注解时代(SpringBoot)
  • 基本的Bean注解,主要是使用注解的方式替代原有的xml的<bean>标签及其标签属性的配置
  • 使用@Component注解替代<bean>标签
    • 被该注解标识的类,会在指定扫描范围内被Spring加载并实例化
  • 具体实例代码
    • 使用注解将目标类注册为bean对象
    • package com.example.DAO.Impl;
      
      import com.example.DAO.UserDAO;
      import org.springframework.stereotype.Component;
      
      @Component(value = "userDAO") // 设置bean对象的名称
      public class UserDAOImpl implements UserDAO {
      }
      
    • 在配置文件中设置注解组件扫描范围,识别@Component注解

    • <?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:context="http://www.springframework.org/schema/context"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
             http://www.springframework.org/schema/beans/spring-beans.xsd
      
             http://www.springframework.org/schema/context
             https://www.springframework.org/schema/context/spring-context.xsd">
          <context:component-scan base-package="com.example.DAO"/>
      </beans>
      
    • 测试代码,获取bean对象

    • package com.example.Test;
      
      
      import org.springframework.context.support.ClassPathXmlApplicationContext;
      
      public class TestApplicationContext {
          public static void main(String[] args) {
              ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
              Object userDAO = context.getBean("userDAO");
              System.out.println(userDAO);
          }
      }
      
      
    • 运行结果如下

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值