前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring-通过注解注入Bean的几种方式(一)

Spring-通过注解注入Bean的几种方式(一)

作者头像
itze
发布2022-10-31 16:01:50
2030
发布2022-10-31 16:01:50
举报
文章被收录于专栏:IT者

用到的注解

  • @Configuration :定义配置类,代替了xml文件
  • @ComponentScan(value = “com.aa”) :包扫描,Spring会自动扫描com.aa同级以及子类包下的所有类
  • @Component : 声明把该类交由Spring,由Spring来帮你完成实例化
  • @Autowired : 注入,Spring完成自动装配

通过构造函数/Set方法/@Autowired方式

AnotherBean.java

代码语言:javascript
复制
/**
 * @Author: www.itze.cn
 * @Email: 814565718@qq.com
 */
//默认为单例模式
@Component
public class AnotherBean {

}

MyBean.java

代码语言:javascript
复制
@Component
public class MyBean {

    private AnotherBean anotherBean1;
    private AnotherBean anotherBean2;
    //使用@Autowired注入
    @Autowired
    private AnotherBean anotherBean3;

    //通过构造方法
    @Autowired
    public MyBean(AnotherBean anotherBean1) {
        this.anotherBean1 = anotherBean1;
    }
    //通过Set方法
    @Autowired
    public void setAnotherBean2(AnotherBean anotherBean2) {
        this.anotherBean2 = anotherBean2;
    }

    @Override
    public String toString() {
        return "MyBean{" +
                "anotherBean1=" + anotherBean1 +
                ", anotherBean2=" + anotherBean2 +
                ", anotherBean3=" + anotherBean3 +
                '}';
    }
}

BeanConfig.java

代码语言:javascript
复制
/**
 * @Author: www.itze.cn
 * @Email: 814565718@qq.com
 */
@Configuration
@ComponentScan(value = "com.example.demo")
public class BeanConfig {

}

测试结果

代码语言:javascript
复制
/**
 * @Author: www.itze.cn
 * @Email: 814565718@qq.com
 */
    public static void main(String[] args) {
        //获取Spring上下文
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanConfig.class);
        MyBean myBean = applicationContext.getBean("myBean", MyBean.class);
        System.out.println("myBean = " + myBean);
        /**
         * 执行结果:
         * myBean = MyBean{anotherBean1=com.example.demo.spring.AnotherBean@2ca47471,
         *                 anotherBean2=com.example.demo.spring.AnotherBean@2ca47471,
         *                 anotherBean3=com.example.demo.spring.AnotherBean@2ca47471}
         * 这里anotherBean1、anotherBean2、anotherBean3的内容时相同,说明是同一个实例,
         * 解释一下,这样是因为在AnotherBean的类上使用@Component注解,默认为单利模式,所以无论谁使用它都是同一个实例
         */
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020年11月19日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 用到的注解
  • 通过构造函数/Set方法/@Autowired方式
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档