java - How to add optional dependency class in spring? -


i'm creating common library , add service uses servletcontext. library should used in cli environment, have find way telling spring ignore servlet there.

@component public class myservice {     //only available in web environment     @autowired(required = false)     private servletcontext servletcontext; }          <dependency>             <groupid>javax.servlet</groupid>             <artifactid>javax.servlet-api</artifactid>             <optional>true</optional>         </dependency> 

in implementation project, want run command line interface, did not include servlet dependency.

but when try launch, following exception thrown on startup: caused by: java.lang.classnotfoundexception: javax.servlet.servletcontext

question: how can make use of servletcontext in commonservice without having add dependency each project reuses class?

just include servlet dependency , make dependency optional you've done. other options worse.

it's light weight class - 93k jar on servlet spec 3.1.0.

but if absolutely must run without class on classpath following...

firstly let me reason you're having issue not because servletcontext field because autowired field. wrote little test app , type of fields of class not required available @ runtime.

so work you'll need profile , named bean.

firstly you're going need inject servletcontext name - , not have typed servletcontext. not great you're going need cast servlet context when need use it.

so

@autowired(required = false) @qualifier("servletcontext") object servletcontext 

is you'll put here.

then create class going provide serlvet context - , turned on via profile - or possibly @membersound referred though @conditionalonwebapplication available in spring boot.

@configuration @profile("web") or @conditionalonwebapplication public class servletcontextprovider {    @autowired   servletcontext servletcontext;      @bean("servletcontext")     public servletcontext getservletcontext() {       return servletcontext;     } } 

like said, include servletcontext on classpath.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -