在Spring Framework中,从Spring 4.3开始,如果目标组件(比如你的RightNowController类)只有一个构造函数,Spring会自动将这个构造函数用作自动装配的构造函数,即使你没有显式地标注它为@Autowired。这意味着,在很多情况下,你确实可以省略@Autowired注解,前提是该类只有一个构造函数。
因此,如果RightNowController类只有一个构造函数,你可以像这样省略@Autowired注解:
package com.ashin.controller;
import com.ashin.client.BotClient;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RightNowController {
private final BotClient botClient;
public RightNowController(BotClient botClient) {
this.botClient = botClient;
}
// 类的其他部分...
}这段代码中,RightNowController的构造函数会自动被用作自动装配的构造函数,Spring将会注入一个BotClient实例,即使没有显式使用@Autowired注解。这样做简化了代码,同时保持了自动装配的功能。
注意事项
单一构造函数:这种省略
@Autowired的方式只适用于只有一个构造函数的类。如果类中有多个构造函数,而你希望其中一个特定的构造函数用于依赖注入,那么这个构造函数必须显式地使用@Autowired注解。一致性:在团队协作的项目中,为了代码的一致性和可读性,有时候仍然推荐显式地使用
@Autowired注解,尤其是当团队成员对Spring的这一特性不是很熟悉时。其他自动装配注解:Spring还提供了其他自动装配的注解,如
@Inject,这是JSR-330标准的一部分。@Autowired和@Inject在大多数情况下是可以互换的,但@Autowired提供了一些额外的特性,比如required属性。
因此,为简化代码,我们可以使用 Lombok 这么写:
@RestController
@AllArgsConstructor
public class RightNowController {
private final QqConfig qqConfig;
private final BotClient botClient;
// ...
}