Spring篇—使用JavaConfig实现配置,一篇文章让你精通关于Spring新的配置Bean方式!

这种纯Java的配置文件,在SpringBoot中随处可见
代码及其注解的作用:

1、定义实体类:

@Component
public class User {
    @Value("1")
    private int id;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                '}';
    }
}

2、编写config.java文件

关于配置Bean的方式,大家尤其关注代码中的注释内容,详细的介绍都在注释中

import com.guohui.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

//@Configuration:声明这个类是一个配置类,相当于之前的applicationContext.xml
@Configuration
//@ComponentScan:扫描某个包下的注解,视为有效状态
@ComponentScan("com.guohui.pojo")
//@Import:相当于applicationContext.xml中的导入其他配置文件的标签,
@Import(MyConfig01.class)
public class MyConfig {
    /*这里的@Bean相当于applicationContext.xml中的<bean/>标签
    * 方法名getUser相当于bean标签中的id
    * 这个方法的返回值return new User(),就相当于bean标签中的class*/
    @Bean
    public User getUser(){
        return new User();
    }
}

3、测试:

public class MyTest {
    @Test
    public void MyTest(){
        //通过JavaConfig的方式配置Bean,则需要用到AnnotationConfigApplicationContext这个上下文对象获取容器
        ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        //这里的getUser就是Config.java中的方法名
        User user = context.getBean("getUser", User.class);
        System.out.println(user.toString());
    }
}

4、控制台:

至此,你就掌握了关于Java中如何通过配置类来进行常见类的注入,通过配置类,你就可以将已有些工作中使用到的某些类注入到Spring容器中,直接在需要使用的业务类中通过@Autowired注解将这个类注入进来就能使用类中的方法了!

预祝各位早日成为Java全栈工程师,后续还会持续更新关于Spring的相关技术栈介绍,敬请期待!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Be explorer

若认可笔者文章,手头富裕望支持

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

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

打赏作者

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

抵扣说明:

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

余额充值