Spring boot application won't run when trying to run from the jar file

前端 未结 3 1831
别跟我提以往
别跟我提以往 2020-12-11 17:13

I have a spring boot application which works fine when run through intellij. But when I run it from the jar I am getting the below exception.

        2017-02         


        
3条回答
  •  不思量自难忘°
    2020-12-11 17:34

    To add onto @Bampfer's answer since Googleing brought me here. This is a way to not have to unpack your resources in a separate module and have dynamic component scanning.

    Create an custom annotation @JaxRsResource that you put on any resource class.

    public @interface JaxRsResource {
    }
    
    @Named
    @JaxRsResource
    @Path("/my/api/path")
    public class MyResource {
        @GET
        public String helloWorld() { return "Hello World"; }
    }
    

    I then utilized spring's component scanning api from this post: Scanning Java annotations at runtime and registered the components I found with my custom annotation and called the register function.

    @Configuration
    public class JaxrsApplication extends ResourceConfig {
    
        private final Logger logger = LoggerFactory.getLogger(JaxrsApplication.class);
    
        public JaxrsApplication() {
    
            final ClassPathScanningCandidateComponentProvider scanner =
                    new ClassPathScanningCandidateComponentProvider(false);
    
            scanner.addIncludeFilter(new AnnotationTypeFilter(JaxRsResource.class));
    
            for (final BeanDefinition resourceBean : scanner.findCandidateComponents("my.base.package")) {
                    try {
                        final Class resourceClass = getClass().getClassLoader().loadClass(resourceBean.getBeanClassName());
                        register(resourceClass);
                    } catch (final ClassNotFoundException e) {
                        logger.error(String.format("Unable to load Jax-RS resource {}.", resourceBean.getBeanClassName()), e);
                    }
                }
            }
        }
    }
    

    Note: You have to load the class from the class loader and pass the Class object to register(). If you only pass the class name as a string to the register method it won't load the resource.

提交回复
热议问题