Spring IoC/DI 08-自动配置注入 Bean

本文介绍Spring框架中自动配置Bean的方法,通过使用@Component、@Repository、@Service、@Controller等注解,自动扫描包并注册Bean,简化了Bean的注入过程。提供了XML和Java配置的示例。

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

自动配置注入 Bean

自动配置的目的

为了使得 Bean 的注入不需要一个一个的配置,可以通过自动配置来简化。

自动配置的实现

为创建为 Bean 的类添加注解

  1. @Component 一般用在身份不明确的组件上
  2. @Repository 一般用在数据库访问层–Dao层/Repository层
  3. @Service 一般用在业务逻辑层–Service层
  4. @Controller 一般用在控制器层–Controller层

示例
UserBean.java

@Component
public class UserBean {
    private String name;
    private int age;

    @Override
    public String toString() {
        return "UserBean{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

UserService

@Service
public class UserService {
    public void sayHello(){
        System.out.println("userService");
    }
}

配置包扫描

如果由多个包需要扫描,多个包可以使用,隔开

在包扫描时,设置属性use-default-filters,可以按照注解过滤扫描的类

  1. true 结合 exclude-filter 标签使用,表示去除某个注解
  2. fase 结合 include-filter 标签使用,表示包含某个注解
XML 配置包扫描示例

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: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 http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="org.daistudy" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
    </context:component-scan>
</beans>

应用

ClassPathXmlApplicationContext context = new 
ClassPathXmlApplicationContext("applicationContext.xml");UserBean userBean = (UserBean) context.getBean("userBean");System.out.println(userBean);
Java 配置包扫描示例

java配置

@Configuration
@ComponentScan(value = "org.daistudy", useDefaultFilters = false, includeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION, value = Service.class)
})
public class JavaConfig {
}

应用

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("org.daistudy.config");
UserBean userBean = (UserBean) context.getBean("userBean");
System.out.println(userBean);
UserService userService = context.getBean(UserService.class);
userService.sayHello();

结果

Spring 容器中没有 userBean 的 Bean,有 userService 的 Bean。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值