一.通过注解注入的一般形式
Bean类
public class TestBean{ }
Configuration类
@Configuration注解去标记了该类,这样标明该类是一个Spring的一个配置类,在加载配置的时候会去加载他。
@Bean的注解,标明这是一个注入Bean的方法,会将下面的返回的Bean注入IOC。
//创建一个class配置文件 @Configuration public class TestConfiguration{ //将一个Bean交由Spring进行管理 @Bean public TestBean myBean(){ return new TestBean(); } }
测试类
ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class); TestBean testBean = cotext.getBean("testBean",TestBean.class); System.out.println("testBean = " + testBean);
二.通过构造方法注入Bean
我们在生成一个Bean实例的时候,可以使用Bean的构造方法将Bean实现注入
Bean类
@Component public class TestBeanConstructor { private AnotherBean anotherBeanConstructor; @Autowired public TeanBeanConstructor(AnotherBean anotherBeanConstructor){ this.anotherBeanConstructor = anotherBeanConstructor; } @Override public String toString() { return "TeanBean{" + "anotherBeanConstructor=" + anotherBeanConstructor + '}'; } }
AnotherBean类
@Component(value="Bean的id,默认为类名小驼峰") public class AnotherBean { }
Configuration类
@Configuration @ComponentScan("com.company.annotationbean") public class TestConfiguration{ }
三.通过set方法注入Bean
@Component public class TestBeanSet { private AnotherBean anotherBeanSet; @Autowired public void setAnotherBeanSet(AnotherBean anotherBeanSet) { this.anotherBeanSet = anotherBeanSet; } @Override public String toString() { return "TestBeanSet{" + "anotherBeanSet=" + anotherBeanSet + '}'; } }
四.通过属性去注入Bean
@Component public class TestBeanProperty { @Autowired private AnotherBean anotherBeanProperty; @Override public String toString() { return "TestBeanProperty{" + "anotherBeanProperty=" + anotherBeanProperty + '}'; } }