gpt4 book ai didi

java - 使用 @autowired 到 DI 后得到一个 null 对象

转载 作者:行者123 更新时间:2023-12-01 16:48:04 25 4
gpt4 key购买 nike

我有一个 utils 类,它使用 @Autowired 使用 spring-boot-starter-data-jpa 注入(inject)存储库。但是当我使用这个存储库访问数据库时,它说存储库为空。我在我的 Controller 中使用了相同的方法,效果很好。这是我的 Utils.class

package com.example.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import com.example.dao.RuleRepository;
import com.example.model.Project;
import com.example.model.Rule;


public class Judge {

@Autowired
RuleRepository ruleRepository;

public boolean ageJudge(Project project) {
try {

if (ruleRepository == null)
{
System.out.println("yes");
}else {
System.out.println("false");
}

return false;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
}

这是我的Application.java

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
@ComponentScan(basePackages = {"com.example"})
public class DemoApplication {

public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

这是RuleRepository.java

package com.example.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.example.model.Project;
import com.example.model.Rule;

public interface RuleRepository extends JpaRepository<Rule, Integer>{
Rule findById(Integer id);
Rule findByRuleName(String ruleName);

}

这是目录。 enter image description here

RuleRepository 在 Controller 中运行良好。那么问题出在哪里呢?

最佳答案

你的util类Judge是一个普通的POJO而不是Spring bean,你只能将Spring bean注入(inject)另一个Spring bean而不是普通的POJO中。

如果您希望在 Judge 中使用 ruleRepository bean,请使用 @Component 注释将其设为 Spring 组件:

@Component
public class Judge {

@Autowired
RuleRepository ruleRepository;

..............................
}

Judge类的User@Service注解充当业务逻辑实现类。

关于java - 使用 @autowired 到 DI 后得到一个 null 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45933602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com