Spring基于注解的零配置支持

本文介绍Spring框架如何通过注解自动装配Bean实例,包括@Component、@Controller、@Service和@Repository等注解的使用方法,以及如何配置Spring自动扫描指定包下的Bean类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、搜索Bean类
为了不再使用Spring的配置文件来配置任何bean实例,Spring自动搜索某些路径下的Java类,并将这些java类注册成Bean实例
Spring提供了如下几个Annotation来标注Spring Bean,目的让Spring知道应该把哪些Java类当成Bean类处理。

  1. @Conponent:标注一个普通的Spring Bean 类
  2. @Controller:标注一个控制器组件类
  3. @Service:标注一个业务逻辑组件类
  4. @Repository:标注一个Dao组件类
    二、使用实例
package com.home.bean;
/**
 * 定义一个接口
 */
public interface Axe {
   public String chop();
}

package com.home.bean;
import org.springframework.stereotype.Component;
@Component
public class SteelAxe implements Axe{

    public String chop() {
        // TODO Auto-generated method stub
        return "钢斧砍柴真的很快";
    }
}

package com.home.bean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
//指定该bean实例的作用域为prototype,不指定默认为singleton
@Scope("prototype")
//指定该类作为spring Bean,Bean实例名为axe
@Component("stoneAxe")
public class StoneAxe implements Axe{
    public String chop() {
        // TODO Auto-generated method stub
        return "石斧砍柴真的很慢";
    }
}

配置文件:
    <context:annotation-config/>
    <!-- 自动扫描指定包及其子包下的所有bean类 -->
    <context:component-scan base-package="com.home.bean">
    <!-- 只是以Axe结尾的类当成Spring容器中的bean -->
    <!-- type:指定过滤器类型
         1.annotation:Annotation过滤器,该过滤器需要指定一个Annotation名,如lee.AnnotationTest
         2.assignable:类过滤器,该过滤器直接指定一个java类
         3.regex,正则表达式过滤器,指定过滤规则,使用如下
         4.aspectJ:AspectJ过滤器,如org.example.*Service+
     -->
    <context:include-filter type="regex" expression=".*Axe"/>
    </context:component-scan>
测试类:
package spring;
import java.util.Arrays;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanTest {
    public static void main(String[] args) {
        //创建spring容器
         ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
         System.out.println("Bean实例名称:"+Arrays.toString(ctx.getBeanDefinitionNames()));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

为你写诗_xue

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值