Ich schreibe eine Spring Boot-Anwendung mit einem REST-Service auf Jersey basiert.Autowired Repository null im Controller für eine Spring Boot-Anwendung
Meine Repository-Schnittstelle ist als unten
@Repository
public interface ConnectionRepository extends CrudRepository<Connection, Integer>
{
}
Mein REST-Service ist als
@Component
@Path("/conn")
public class ConnectionService
{
@Autowired
private ConnectionRepository cer;
@GET
@Path("/{id}/")
@Produces(MediaType.APPLICATION_JSON)
public Response getSpConnection(@PathParam("id") String tid) throws Exception
{
Gson gson = new Gson();
if(cer == null)
{
return Response.status(Response.Status.OK).entity("Hello World").build();
}
Connection conendpoint = cer.find(tid);
if(conendpoint == null)
{
return Response.status(Response.Status.NOT_FOUND).build();
}
else
{
String jsonConn = gson.toJson(conendpoint);
return Response.status(Response.Status.OK).entity(jsonConn).build();
}
}
}
Application.java folgt
@EnableAutoConfiguration
@SpringBootApplication
@ComponentScan
@Component
@PropertySource("classpath:/application.properties")
@Import(PersistenceContext.class)
public class Application extends SpringBootServletInitializer
{
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(applicationClass);
}
private static Class<Application> applicationClass = Application.class;
public static void main(String[] args)
{
SpringApplication.run(Application.class, args);
}
}
PersistenceContext enthält Informationen für Datenquelle und anderen Bohnen.
Jedes Mal, wenn ich diesen REST-Dienst zugreifen, bekomme ich ConnectionRepository als null und die Antwort ist „Hallo Welt“. Ich verwende spring-boot-starter-web
, spring-boot-starter-jersey
und spring-boot-starter-data-jpa
.
Was fehlt mir?
sicherstellen, dass das Paket von ConnectionRepository & Connection eine gleiche oder subpackage von Application.java ist – lenicliu
Zeigen Sie Ihre Anwendungskonfiguration. Sie sollten die Annotation "@ SpringBootApplication" verwenden, das Repository im selben Paket wie die mit Annotationen versehene Klasse haben und die Annotation "@ Repository" aus der Schnittstelle entfernen. Stellen Sie außerdem sicher, dass eine Datenquelle konfiguriert ist oder die automatische JPA-Konfiguration nicht aktiviert ist. – Strelok
@lenicliu - Application.java befindet sich im com.example.connection-Paket, ConnectionRepository in com.example.connection.repositories und ConnectionService in com.example.connection.rest – yogsma