【问题标题】:Autowired field is null in spring boot applicationSpring Boot 应用程序中的 Autowired 字段为空
【发布时间】:2016-03-10 07:55:52
【问题描述】:

我正在实现一个简单的 Spring Boot 应用程序:

Content类:

Entity
@Table(name = "content")
public class Content implements Serializable {

public Content() {
}

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;

@NotNull
private String title;

//getter/setter and toString()
}

ContentRepository接口:

@Repository
public interface ContentRepository extends CrudRepository<Content, Long>{
}

RepositoryConfiguration:

@Configuration
@EnableJpaRepositories({"com.tarameshgroup.derakht.repository"})
@EntityScan("com.tarameshgroup.derakht.domain")
@ComponentScan("com.tarameshgroup.derakht")
public class RepositoryConfiguration {
}

Application 测试类:

@SpringBootApplication
@EnableAutoConfiguration
@Import({RepositoryConfiguration.class})
public class Application {

    private static final Logger logger = org.slf4j.LoggerFactory.getLogger(Application.class);

    @Autowired
    static ContentRepository contentRepository; // Why is null?

    public static void main(String[] args) {
        logger.info("Running application...");
        SpringApplication.run(Application.class);

        System.out.println("contentRepository: " + contentRepository); //why contentRepository is null?
    }

【问题讨论】:

  • 实现接口ContentRepository的类在哪里。 AS 当您创建实现类的自动装配对象时。因为我看不到任何实现它的类。这就是错误的原因
  • @Naruto 在spring boot 应用程序中不需要实现类。

标签: java spring spring-boot spring-data


【解决方案1】:

您将 ContentRepository 定义为静态字段。要么让它成为非静态的,要么使用这个技巧@autowired in static classes

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-06
    • 2018-11-11
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 2022-01-04
    相关资源
    最近更新 更多