Spring 通过构造方法注入对象

Spring 通过构造方法注入对象

今天在看一段代码的时候,觉得很奇怪如下:

public class NitroEnclaveServer {
          
   

	private static final Logger LOG = LoggerFactory.getLogger(NitroEnclaveServer.class);

	private final Listener clientListenerPort;

	private final ListenerConsumer listenerConsumer;

	public NitroEnclaveServer(Listener clientListenerPort, ListenerConsumer listenerConsumer) {
          
   
		this.clientListenerPort = clientListenerPort;
		this.listenerConsumer = listenerConsumer;
	}
}

直接通过构造方法就可以注入这个对象了????下面做了一个测试

验证

一个实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class TestEntity {
          
   
    private String name;
    private String value;
}

配置类:

@Configuration
public class MyConfig {
          
   
    @Bean
    public TestEntity testEntity() {
          
   
        return new TestEntity("zhangsan","23");
    }
}

service类:

public interface TestEntityService {
          
   

}
@Service
public class TestEntityServiceImpl implements TestEntityService {
          
   

}

测试类:

@RestController
public class TestController {
          
   

    private final TestEntity testEntity;
    private final TestEntityService testEntityService;

    public TestController(TestEntity testEntity, TestEntityService testEntityService) {
          
   
        this.testEntityService = testEntityService;
        this.testEntity = testEntity;
    }
}

启动打断点:

发现是可以获取的,并且不用加上 @Autowired 注解。

下面验证一下是不是从容器中获取的:

@RestController
public class TestController {
          
   
    @Autowired
    private ApplicationContext applicationContext;

    private final TestEntity testEntity;
    private final TestEntityService testEntityService;

    public TestController(TestEntity testEntity, TestEntityService testEntityService) {
          
   
        this.testEntityService = testEntityService;
        this.testEntity = testEntity;
    }

    @PostMapping("/test")
    public String testDemo(@RequestBody TestEntity entity) {
          
   
        return entity.getName();
    }
}

发请求: 发现: 发现是从容器里面获取的。

经验分享 程序员 微信小程序 职场和发展