Spring注解 之装配Bean

简介

Spring IoC 容器是一个管理 Bean 的容器,在 Spring 的 定义中,它要求所有的 IoC 容器都需要实现接口 BeanFactory ,它是一个顶级容器接口 。

在现实中使用的大部分 Spring IoC 容器是 ApplicationContext 接口的实现类。
在这里插入图片描述

在 Spring Boot 当中主要是通过注解来装配 Bean 到 Spring IoC 容器中,AnnotationConfigApplicationContext就是一个基于注解的 IoC 容器。

使用@Bean注解装配Bean

Java对象。

@Setter
@Getter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String userName;
}

配置类。

import com.demo.entity.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    @Bean(name = "user")
    public User user(){
        return new User();
    }

}

测试类。

@Test
public void test(){
    AnnotationConfigApplicationContext applicationContext =
            new AnnotationConfigApplicationContext(AppConfig.class);
    User bean = applicationContext.getBean(User.class);
    System.out.println(bean);
}

使用包扫描@ComponentScan装配Bean

在配置类上添加@ComponentScan指定包扫描的范围。

@Configuration
@ComponentScan(basePackages = "com.demo.entity")
public class AppConfig {

}

在实体类上添加@Component注解表示需要装配到IOC容器。

@Component
public class User {
    private String userName;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值