开发者

Using @Async or @Scheduled in non-singletons

Need some quick help.

  1. Is it possible to make a class annotated with @Service to be a non-singleton, 开发者_C百科in a way that I can use Clazz c = new Clazz(); and it creates a new object?

  2. 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.


  1. 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.

  2. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜