用于Spring Boot应用程序的Controller中的Autowired Repository null

时间:2016-11-24 17:08:59

标签: rest spring-boot spring-data

我正在编写一个Spring Boot应用程序,其中包含基于jersey的REST服务。

我的存储库界面如下

@Repository
public interface ConnectionRepository extends CrudRepository<Connection, Integer>
{


}

我的REST服务如下

@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

@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包含数据源和其他bean的信息。

每当我访问此REST服务时,我将ConnectionRepository视为null,响应为“Hello World”。我使用的是spring-boot-starter-webspring-boot-starter-jerseyspring-boot-starter-data-jpa

我错过了什么?

1 个答案:

答案 0 :(得分:1)

我通过在我的pom.xml

中添加以下依赖项解决了这个问题
    <dependency>
        <groupId>org.glassfish.jersey.ext</groupId>
        <artifactId>jersey-spring3</artifactId>
        <version>2.23.2</version>
        <exclusions>
            <exclusion>
                <groupId>org.springframework</groupId>
                <artifactId>spring</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
            </exclusion>
        </exclusions>
    </dependency>