Using @Async or @Scheduled in non-singletons
Need some quick help.
Is it possible to make a class annotated with
@Service
to be a non-singleton, 开发者_C百科in a way that I can useClazz c = new Clazz();
and it creates a new object?If not: Is it possible to use
@Async
and@Scheduled
in a class that is not annotated with@Component
or@Service
?
cheers!
If you want a non-singleton, spring-managed object, declare it with scope="prototype"
(or @Scope("prototype")
. If you want to inject prototype-scoped beans into a singleton, you can use a lookup-method
. A new object will be returned on each invocation of the method. this is how it is done with xml.
You can have objects that you instantiate managed by spring by using an aspectj weaver and @Configurable
, but it's not something I'd recommend.
You can have @Async
and @Scheduled
on any spring-managed bean. There are multiple ways to define it as such: annotation (@Service
), xml config, or java config.
The benefit of
@Service
is that Spring will auto-discover, instantiate and manage the bean for you. If they're not singletons, there's no benefit to this annotation.Yes.
@Async
and@Scheduled
have nothing to do with@Service
and@Component
Yes, you can instantiate classes marked as@Service
, just because Spring creates a single instance of it doesn't mean you can't create others.
精彩评论