spring-boot - @Qualifier 和 @Autowired 对象为 null
问题描述
我在下面有以下代码。
@Builder(toBuilder = true)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@ToString
@EqualsAndHashCode
@Configurable
public class Employee {
@Autowired
@Qualifier("findEmpByDepartment")
private Function<Long, Long> empByDepartment;
private void save() {
this.empByDepartment.getList();
}
}
和下面的FindEmpByDepartment类。
@Component("findEmpByDepartment")
public class FindEmpByDepartment implements Function<Long, Long> {
public void getList() {
}
....
}
我的问题是调用时我总是得到空值
this.empByDepartment.getList();
线。这里this.empByDepartment是空的。知道为什么会这样吗?
谢谢
解决方案
您可能会错过注释流层次结构中的任何类。
@Service、@Repository 和 @Controller 都是 @Component 的特化,所以任何你想自动连接的类都需要用其中之一进行注解。
IoC 就像一个很酷的孩子,如果您使用 Spring,那么您需要一直使用它。
因此,请确保您在整个流程中没有使用 new 运算符创建任何对象。
@Controller
public class Controller {
@GetMapping("/example")
public String example() {
MyService my = new MyService();
my.doStuff();
}
}
@Service
public class MyService() {
@Autowired
MyRepository repo;
public void doStuff() {
repo.findByName( "steve" );
}
}
@Repository
public interface MyRepository extends CrudRepository<My, Long> {
List<My> findByName( String name );
}
这将在服务类尝试访问 MyRepository 自动连接的存储库时引发 NullPointerException,这不是因为存储库的接线有任何问题,而是因为您使用 MyService my = new MyService() 手动实例化了 MyService()。
有关更多详细信息,您可以查看 https://www.moreofless.co.uk/spring-mvc-java-autowired-component-null-repository-service/
推荐阅读
- sql - 从 WITH 子句中选择查询太慢 Oracle
- javascript - How to sort alphabetically an array of object depending on name and a query string?
- node.js - Puppeteer 没有点击放置在里面的按钮
- 标签
- c# - 我将如何在这里使用 GET 请求?
- sql - 如何解决 Oracle Apex 中的无效列错误?
- flutter - 将 Flutter 小部件定位到屏幕外
- python - 无法从 Python fdb 中以“@”开头的表中进行选择
- c# - 正则表达式 qoute 多级 C#/VB
- node.js - Firebase 响应返回 200 但为空数组
- sql - 我可以从 MS SQL Server 的地址列中按状态过滤行吗?