赞
踩
1. 构造器方法注入
2. 字段注入
3. 属性或普通方法注入
注意:后面的注入会覆盖前面的值
- package com.jade.spring.context.annotation7;
-
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
-
- @Configuration
- public class ConfigForRegister {
-
- @Bean
- String fieldInject() {
- return "属性注入值";
- }
-
- @Bean
- String constructorInject() {
- return "构造器注入值";
- }
-
- @Bean
- String methodInject() {
- return "方法注入值";
- }
-
- @Bean
- String anotherMethodInject() {
- return "另一个方法注入值";
- }
- }
- package com.jade.spring.context.annotation7;
-
- import javax.inject.Named;
-
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Component;
-
- @Component
- public class InjectOrder {
-
- @Autowired
- @Named("fieldInject")
- String log;
- {
- log = "手动属性赋值";
- System.out.println(log);
- }
-
- @Autowired
- public InjectOrder(@Named("constructorInject") String log) {
- System.out.println();
- System.out.println("进入构造器《="+this.log);
- System.out.println("第一步:构造器注入=》"+log);
- this.log = "手动构造器赋值";
- System.out.println(this.log);
- }
-
- @Autowired
- public void setValue(@Named("methodInject") String log) {
- System.out.println();
- System.out.println("进入方法《="+this.log);
- System.out.println("第三步:方法注入=》"+log);
- this.log = "手动方法赋值";
- System.out.println(this.log);
- }
-
- @Autowired
- public void setValue2(@Named("anotherMethodInject") String log) {
- System.out.println();
- System.out.println("再次进入方法《="+this.log);
- System.out.println("再次方法注入=》"+log);
- this.log = "再次手动方法赋值";
- System.out.println(this.log);
- }
-
- public String getValue() {
- return log;
- }
- }
- package com.jade.spring.context.annotation;
-
- import org.junit.Test;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.annotation.AnnotationConfigApplicationContext;
-
- import com.jade.spring.context.annotation7.ConfigForRegister;
- import com.jade.spring.context.annotation7.InjectOrder;
-
- public class InjectionOrderTest {
-
- @Test
- public void testInjectionOrder() {
- @SuppressWarnings("resource")
- ApplicationContext context = new AnnotationConfigApplicationContext(InjectOrder.class, ConfigForRegister.class);
- InjectOrder bean = context.getBean(InjectOrder.class);
- System.out.println(bean.getValue());
- }
- }
结果如下:
- 手动属性赋值
-
- 进入构造器《=手动属性赋值
- 第一步:构造器注入=》构造器注入值
- 手动构造器赋值
-
- 进入方法《=属性注入值
- 第三步:方法注入=》方法注入值
- 手动方法赋值
-
- 再次进入方法《=手动方法赋值
- 再次方法注入=》另一个方法注入值
- 再次手动方法赋值
-
- 再次手动方法赋值
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。