注释@Autowired 出现问题。如何决定?

有一段代码:


package com.example.sweater3.domain;


import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;


@Entity

public class Message {

    @Id

    @GeneratedValue(strategy=GenerationType.AUTO)

    private Integer id;


    private String text;

    private String tag;


    public Message() {

    }


    public Message(String text, String tag) {

        this.text = text;

        this.tag = tag;

    }


    public void setText(String text) {

        this.text = text;

    }


    public String getText() {

        return text;

    }


    public Integer getId() {

        return id;

    }


    public void setId(Integer id) {

        this.id = id;

    }


    public String getTag() {

        return tag;

    }


    public void setTag(String tag) {

        this.tag = tag;

    }

}

_


package com.example.sweater3.repos;


import com.example.sweater3.domain.Message;

import org.springframework.data.repository.CrudRepository;

import org.springframework.stereotype.Repository;


import java.util.List;


@Repository

public interface MessageRepo extends CrudRepository<Message, Long> {


    List<Message> findByTag(String tag);

}

__


package com.example.sweater3;


import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication

public class Application {

    public static void main(String[] args) {

        SpringApplication.run(Application.class, args);

    }

}

__


package com.example.sweater3;


import com.example.sweater3.repos.MessageRepo;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;


@Controller

public class GreetingController {


    @Autowired

    private MessageRepo messageRepo;

}

交互式爱情
浏览 88回答 1
1回答

红颜莎娜

您必须在应用程序中启用存储库:@SpringBootApplication@EnableJpaRepositoriespublic class Application {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; SpringApplication.run(Application.class, args);&nbsp; &nbsp; }}另请确保添加:<dependency>&nbsp; &nbsp; &nbsp;<groupId>org.springframework.boot</groupId>&nbsp; &nbsp; &nbsp;<artifactId>spring-boot-starter-data-jpa</artifactId>&nbsp; &nbsp; &nbsp; &nbsp;</dependency>更新:您必须配置数据库连接和驱动程序。H2 示例(在内存数据库中)添加新的依赖项:<dependency>&nbsp; &nbsp; &nbsp;<groupId>com.h2database</groupId>&nbsp; &nbsp; &nbsp;<artifactId>h2</artifactId>&nbsp; &nbsp; &nbsp;<scope>runtime</scope></dependency>在 application.properties 中添加:spring.datasource.url=jdbc:h2:mem:testdbspring.datasource.driverClassName=org.h2.Driverspring.datasource.username=rootspring.datasource.password=rootspring.jpa.database-platform=org.hibernate.dialect.H2Dialect
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java