用到的注解

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

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

AnotherBean.java

/**
* @Author: www.itze.cn
* @Email: 814565718@qq.com
*/
//默认为单例模式
@Component
public class AnotherBean {

}

MyBean.java

@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

/**
* @Author: www.itze.cn
* @Email: 814565718@qq.com
*/
@Configuration
@ComponentScan(value = "com.example.demo")
public class BeanConfig {

}

测试结果

/**
* @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注解,默认为单利模式,所以无论谁使用它都是同一个实例
*/
}