Quote from spring-cloud-doc:
The RefreshScope is a bean in the context and it has a public method refreshAll() to refresh all beans in the scope by clearing the target cache. There is also a refresh(String) method to refresh an individual bean by name. This functionality is exposed in the /refresh endpoint (over HTTP or JMX).
How could I invoke the /refresh endpoint to refresh an individual bean (#RefreshScope) by name? The source code of spring-cloud-commons didn't tell me that. Or I understand "this functionality" wrong.
Related
Can anyone explain to me the difference between calling resourceResolver by annotating #ScriptVariable and by annotating #SlingObject? In what context do they behave differently?
The key difference is in the way the object is retrieved. #ScriptVariable and #SlingObject are injector-specific annotations. This means that you can use them to instruct Sling Models to use a particular injector.
The injector that recognises the #ScriptVariable annotation can inject objects available as Scripting Variables. In case ot the resourceResolver, it should be the one associated with the request. Same as slingRequest.getResourceResolver().
Looking at the code, the injector that kicks in on fields annotated with #SlingObject is a bit more interesting in that it will inspect the adaptable (from which your Sling Model is being adapted) and obtain the resolver accordingly:
If the adaptable is a Resource, it'll return resource.getResourceResolver(), i.e. the resolver originally used to load the resource. This may be quite aribtrary.
If the adaptable is a SlingHttpServletRequest, it'll return request.getResourceResolver(), i.e. the resolver instantiated by Sling in association with the request and the session of the user issuing the request.
If the adaptable itself is a ResourceResolver, it will be returned directly.
In some cases, the difference between the three will be negligible, but sometimes it will be important which resolver you choose. If your model is, for example, supposed to be used outside the scope of a request (imagine it's instantiated by an OSGi service that runs on a schedule and there's no incoming request), you'll be better off using resource or resourceResolver as an adaptable.
I've the following question:
ContainerRequestFilter is a singleton, but reading this:
Jaxrs-2_0 Oracle Spec
in chapter 9.2, they say:
Context is specific to a particular request but instances of certain JAX-RS components (providers and resource classes with a lifecycle other than per-request) may need to support multiple concurrent requests. When injecting an instance of one of the types listed in Section 9.2, the instance supplied MUST be capable of selecting the correct context for a particular request. Use of a thread-local proxy is a common way to achieve this.
In the chapter 9.2, the HttpServletRequest is not mentioned.
So the question is: is it safe in terms of concurrency to inject the HttpServletRequest inside a custom ContainRequestFilter?
I mean this:
#Provider
#PreMatching
public class AuthenticationFilter implements ContainerRequestFilter {
#Context private HttpServletRequest request;
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
// This is safe because every thread call the method with its requestContext
String path = requestContext.getUriInfo().getPath(true);
// Is this safe? The property request is injected by using #Context annotation (see above)
String toReturn = (String)request.getAttribute(name);
[...]
}
I did some empirical tests on my IDE in debug mode, sending with two different browsers two different and concurrent requests and it seems to work well; I noticed that the filter's instance is ever the same (it's a singleton), but the injected HttpServletRequest is different in the two cases.
I readed even this thread: How to access wicket session from Jersey-2 request filter? and it seems that my tests are confirmed.
But I still have doubts.
Confirm?
Yes it's safe. To understand the problem, you should understand how scopes work. In any framework that deals with scopes (and injection), the feature is implemented similarly. If an object is in a singleton scope and another object in a lesser scope needs to be injected, usually a proxy of the object will be injected instead. When a call is made on the object, it's actually a call on the proxy.
Though the spec may not mention the HttpServletRequest specifically, most JAX-RS implementation have support for this. With Jersey in particular, if this was not possible (meaning the object is not proxiable), then you would get an error message on startup with something like "not within a request scope". The reason is that the ContainerRequestFilter is created on app startup, and all the injections are handled at that time also. If the HttpServletRequest was not proxiable, it would fail to inject because on startup, there is no request scope context.
To confirm that it is not the actual HttpServletRequest and is a proxy, you can log the request.getClass(), and you will see that it is indeed a proxy.
If you are unfamiliar with this pattern, you can see this answer for an idea of how it works.
See Also:
Injecting Request Scoped Objects into Singleton Scoped Object with HK2 and Jersey
We are using partitioner and it is annotated with #Scope(value="step") and has setter method which is annotated with #BeforeStep, but still framewowrk does not inject step execution object?
What we are doing wrong
Did you register the partitioner as "listener" on the step? As soon as you are using Step-Scope, your Bean is hidden behind a proxy, which makes it impossible for spring to register it automatically as a step-listener (it should work if your bean is not "step-scoped").
It is explained here:
Spring-batch #BeforeStep does not work with #StepScope
I have a java class, call it "Job", that implements an interface that I export as a service using blueprint. Although the class is defined as a bean with scope="prototype" in the blueprint xml file, and the service referen ces that bean, I can see from a System.out.println(this) statement in an instance method of the Job, that each time I access the service from a caller bundle, it reuses the same instance of the class Job that it created when I start the bundle; my caller bundle looks up the service references, calls context.getService(serviceReferences[0]) to get the reference to the Job service and then calls the method on that service (eg. Job.run()).
I thought making the scope of the service bean def prototype would give me a new instance of Job each time I called getService from the caller bundle, but my experiments are showing me that it's still using the same object instance.
So how do I call the service and have it create a new instance of Job each time, rather than reusing the same object?
I also need another service reference injected as a property into the bean Job since the bean interface doesn't have a set method to do this. So each new instance has to be created as the bean Job so that it can inject the property with a setX() method.
If you use prototype scope for a bean, it means that a new instance will be created every time the bean is injected to another bean / service within the same blueprint container.
In your case a new instance of a bean is created as it is injected into the service component. However, the service component can provide only the same instance every time it is requested by another bundle.
For me it seems to me that you try to use blueprint and prototype scope for a task that should be done programmatically. You want to use a service that creates a new instance every time. That means that you should define a JobFactory interface and its implementation and register it as an OSGi service. On the other side, you should use JobFactory to instantiate as many Job instances as you want.
You could also use PrototypeServiceFactory but you have to register it programmatically as well. In my opinion, when someone wants to use PrototypeServiceFactory, it is time to extend the API with a Factory.
Does anyone have a working example of sharprepository intergration with autofac using InstancePerApiRequest for DbContext?
I am registering my dbcontext thusly:
builder.RegisterType<AuditTestEntities>().As<DbContext>().InstancePerApiRequest();
If I remove the InstancePerApiRequest, sharprepository is able to get a dbcontext. But with the InstancePerApiRequest, I get the error message pasted below. Basically the crux of the error is, I suspect, the way sharprepository makes the call:
No scope with a Tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested. This generally indicates that a component registered as per-HTTP request is being requested by a SingleInstance() component (or a similar scenario.) Under the web integration always request dependencies from the DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime, never from the container itself.
The full error stack:
iisexpress.exe Error: 0 : Operation=DefaultHttpControllerActivator.Create, Exception=System.InvalidOperationException: An error occurred when trying to create a controller of type 'AccountController'. Make sure that the controller has a parameterless public constructor. ---> Autofac.Core.DependencyResolutionException: An exception was thrown while invoking the constructor 'Void .ctor()' on type 'AccountRepository'. ---> Could not resolve type 'System.Data.Entity.DbContext' using the 'AutofacDependencyResolver'. Make sure you have configured your Ioc container for this type. View the InnerException for more details. (See inner exception for details.) ---> SharpRepository.Repository.Ioc.RepositoryDependencyResolverException: Could not resolve type 'System.Data.Entity.DbContext' using the 'AutofacDependencyResolver'. Make sure you have configured your Ioc container for this type. View the InnerException for more details. ---> Autofac.Core.DependencyResolutionException: No scope with a Tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested. This generally indicates that a component registered as per-HTTP request is being requested by a SingleInstance() component (or a similar scenario.) Under the web integration always request dependencies from the DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime, never from the container itself.
Okay found the issue. There is a problem with using the SharpRepository AutofacDependencyResolver when using the MVC or Web API integration and trying to use the scope InstancePerApiRequest or InstancePerHttpRequest. Autofac expects those items to be resolved from the System.Web.DependencyResolver.Current instead of from the Autofac IContainer directly as the AutofacDependencyResolver is currently doing.
Here is how you can fix the issue right now until we make an overload for AutofacDependencyResolver that fixes the issue.
You will need to create your own dependency resolver within your project like this one:
public class CustomAutofacDependencyResolver : BaseRepositoryDependencyResolver
{
private readonly IDependencyResolver _resolver;
public CustomAutofacDependencyResolver(IDependencyResolver resolver)
{
_resolver = resolver;
}
protected override T ResolveInstance<T>()
{
return _resolver.GetService<T>();
}
protected override object ResolveInstance(Type type)
{
return _resolver.GetService(type);
}
}
And then register it with SharpRepository so it will use it to resolve the DbContext and then it will work as expected.
RepositoryDependencyResolver.SetDependencyResolver(new CustomAutofacDependencyResolver(DependencyResolver.Current));
** Update**
I was testing with MVC and able to replicate the error and fix it but that doesn't work with Web API. I am used to using StructureMap where it works fine using the GlobalConfiguration.Configuration.DependencyResolver.
It seems the issue is that Autofac needs a IDependencyScope that you can access from the HttpRequestMessage but I'm not seeing a way to get to that outside of the ApiController. This describes the issue and the reason: https://groups.google.com/forum/#!msg/autofac/b3HCmNE_S2M/oMmwFE5uD80J
Unfortunately right now I'm at a bit of a loss on the best way to handle this. But I'll keep thinking about it.
So, I was able to get mine working by changing the lifetime scope to InstancePerLifetimeScope. I don't know whether this has any unforeseen consequences or not. Everything appears to be working fine for me so far.