In the reference implementation of the JAX-RS Whiteboard for OSGi, what calls createWhiteboard(..)? - osgi

The reference implementation of OSGi's JAX-RS Whiteboard is called Aries JAX-RS Whiteboard.
My question is, how and when does the factory method for the Whiteboard.class get called?
public static Whiteboard createWhiteboard(
Dictionary<String, ?> configuration) {
return new Whiteboard(configuration);
}
Like, for example, if I drop the jar into an Apache Felix instance?
I searched the whole project for the createWhiteboard symbol, but I did not find anything calling it. I know it is OSGi Runtime that does this, but how, where?

Ok, so I answered my own question.
The Whiteboard.class is called by a separate "activator" class that implements the standardized OSGi callback interface, BundleActivator: CxfJaxrsBundleActivator at line 76. This is analogous to the entry point of a program. Then, at line 105, the runWhiteboard method is called, which abstracts away the call to createWhiteboard use a method that is perhaps way more complicated than it should be starting at line 198.
The main calls in the stack in bottom-up order would be:
createWhiteboard(configuration)
runWhiteboard(bundleContext, configuration)
start(BundleContext bundleContext) throws Exception

Related

Factory design pattern and Spring

I am wondering what is the current best practice as to the use of factory pattern within the context of Spring framework in using dependency injection. My wonder arises about whether the factory pattern is still relevant nowadays in light of the use of Spring dependency injection. I did some searching and see some past discussion (Dependency Injection vs Factory Pattern) but seem there is different view.
I see in some real life project in using a Map to hold all the beans and rely on autowiring to create those beans. When the bean is needed, it get it via the map using the key.
public abstract class Service {
//some methods
}
#Component
public class serviceA extends Service {
//implementation
}
#Component
public class serviceB extends Service {
//implementation
}
Map<String, Service> services;
But I see there is some difference among the two approaches.
Using the above method, all beans are created on application start up and the creation of object is handled by the framework. It also implies there is only one bean for each type.
While for factory pattern, the factory class creates the object on request. And it can create a new object for each request.
I think a deeper question may be, when Spring framework is used in a project, should it be strived to not create any object inside a class, which means the factory pattern ( or any creational design patterns?) should not be used, as Spring is supposed to be the central handler of the objects dependency ?
The answer to this question can be really deep and broad, I'll try to provide some points that hopefully will help.
First off, spring stores its beans (singletons) in the ApplicationContext. Essentially this is the map you're talking about. In a nutshell, it allows getting the bean by name, type, etc.
ApplicationContext, while being a really important concept, is not the whole Spring, in fact Spring framework allows much more flexibility:
You say, using a map implies that all the beans will be created at the beginning of the application and there is one instance of the bean.
Spring has a concept of Lazy beans, basically supporting a concept of beans being actually created only when they're required for the first time, so Spring supports the "delayed" beans initialization
Spring also allows more than one instance of a bean per type. So this map is more "advanced". For example you can create more than one implementation of the interface and use declare both as beans. As long as you provide enough information about what bean should be injected to the class that might use them (for example with a help of qualifiers suppored in spring), you're good to go. In addition, there are features in spring IoC container that allow injecting all registered implementations of an interface into a list:
interface Foo {}
#Component
class FooImpl1 implements Foo {}
#Component
class FooImpl2 implements Foo {}
class Client {
#Autowired
List<Foo> allFoos;
}
Now you say:
While for factory pattern, the factory class creates the object on request. And it can create a new object for each request.
Actually Spring can create objects per request. Not all beans have to be singletons, in general spring has a concept of scopes for this purposes.
For example, scope prototype means that Spring will create a bean upon each usage. In particular one interesting usage that spring supports in variety of ways is Injecting prototype bean into singleton. Some solutions use exactly like a factory (read about annotation #Lookup others rely on auto-generated proxy in runtime (like javax.inject.Provider). Prototype scope beans are not held in the application context, so here again spring goes beyond a simple map abstraction.
Last feature that you haven't mentioned is that sometimes even for singletons the initialization can be a little bit more complicated then calling a constructor with Parameters. Spring can address that by using Java Configurations:
#Configuration
public class MyConfig {
public SomeComplicatedObject foo(#Value("...") config, Bar bar) {
SomeComplicatedObject obj = new SomeComplicatedObject() // lets pretend this object is from some thirdparty, it only has no-op constructor, and you can't place spring annotations on it (basically you can't change it):
obj.setConfig(config);
obj.setBar(bar);
return obj;
}
}
The method foo here initializes the object SomeComplicatedObject and returns it. This can be used instead of factories to integrate "legacy" code (well, java configurations go way beyond this, but its out of scope for this question).
So bottom line, you Spring as an IoC container can provide many different ways to deal with object creation, in particular it can do everything that factory design pattern offers.
Now, I would like to also refer to your last sentense:
I think a deeper question may be, when Spring framework is used in a project, should it be strived to not create any object inside a class, which means the factory pattern ( or any creational design patterns?) should not be used, as Spring is supposed to be the central handler of the objects dependency ?
Indeed you don't have to use Factory Pattern when using Spring, since (as I hopefully have convinced you) provides everything that factory can do and more.
Also I agree that spring is supposed to be the central handler of the objects dependency (unless there are also parts of the application which are written in a different manner so you have to support both :) )
I don't think we should avoid using "new" altogether, not everything should/can be a bean, but I do see (from my subjective experience, so this is arguable) that you use it much less leaving the creation of most of the objects to Spring.
Should we avoid a usage of any creation design pattern? I don't think so, sometimes you can opt for implementing "builder" design pattern for example, its also a creational pattern but spring doesn't provide a similar abstraction.
I think if your project uses Spring framework you should use it. Although it depends on your project design e.g. You may use creational patterns along side with Spring IoC. e.g when you have abstraction layers not framework dependant (agnostic code)
interface ServiceFactory {
Service create(String type);
}
#Component
class SpringServiceFactory implements ServiceFactory {
#Autowired private ApplicationContext context;
Service create(String type) {
return context.getBean(type)
}
}
I use Factory pattern as well when I refactor legacy not unit testable code which also uses Spring Framework in order to implement unit tests.
// legacy service impossible to mock
class LegacyApiClient implements Closeable {...}
#Component
class LegacyApiClientFactory {
LegacyApiClient create(String endpoint) {
return new LegacyApiClient(endpoint);
}
}
#Component
class OtherService {
private final String endpoint
private final LegacyApiClientFactory factory;
OtherService(#Value("${post.endpoint}") String endpoint,
LegacyApiClientFactory factory) {...}
void doCall {
try (LegacyApiClient client = factory.create(endpoint)) {
client.postSomething();
}
}
}
....
// a random unit test
LegacyApiClient client = mock(LegacyApiClient.class)
LegacyApiClientFactory factory = mock(LegacyApiClientFactory.class)
OtherService service = new OtherService("http://scxsc", factory);
when(factory.create(any())).thenReturn(client)
service.doCall()
....

Spring How its helpful [duplicate]

This question already has answers here:
What is dependency injection?
(37 answers)
Closed 7 years ago.
I have a class
#Component
public class MessageServiceHelper {
#Autowired
private MessageService messageService;
public boolean sendMessage(String text){
return messageService.sendMessage(text);
}
public MessageService getMessageService() {
return messageService;
}
public void setMessageService(MessageService messageService) {
this.messageService = messageService;
}
}
so here I am autowiring messageService, so that whenever the object ob MessageServiceHelper is instantiated then it will automatically inject dependency messageService into MessageServiceHelper. Same thing I can achieve if I have write some other class which will create the instance of MessageService and will call the setter method.
Now here the point can be raised is we have shifted the dependency resolution logic some where else and that code is coupled with the instantiation of MessageService and if some implementation is changed then I will have to change that class but with spring also If I have to change implementation I have to make change in metadata that I have given before.
so here my question is what is different with DI? What is strongest point about DI here?
In short, the metadata change is desirable which enables configuration of a higher layer of abstraction rather than change in the application code. The configurable higher layer is then reusable and your lower layer of application code is easily testable. Dependency injection is one of the very old core design principles featuring in famous SOLID design principles. This design principle has featured into lots of frameworks out there - Spring being one of the most popular and evangelist of DI in Java world. There are already lots of good articles available to understand the necessity of DI- you can read them on Wikipedia and Microsoft library. And yes, then there are few gem of articles on Martin Fowler's site to understand it in depth here and here.
The point of dependency injection is reuse. Crafting your code correctly you can inject multiple implementations at runtime.
This is particularly useful for unit testing where you want to pass a mock object instead of a real one without modifying the object. By moving the dependency outside of the code and injecting it you can test your code without modifying it.
It also allows a separation of concerns. If the creation of the object is a complex affair you don't have to put that code in the class which uses it. Other code or classes can do the creation and just pass it into your class, which no longer has to worry about the specifics of how it was created. So moving it outside is an advantage. Think of complex objects created using frameworks. Good examples include instantiating a database driver or database session.
There are other specific instances where the reuse is practical but I would say these are the main ones I've seen for web applications and business code.

Is there any way to intercept all Linq to SQL queries?

I've built some code that can rebuild expression trees so I can avoid triggering the no supported translation to SQL exception and it works fine as long as I call my function to replace the iqueryable. The problem is that I'd like it to automatically be applied to all queries in my project without having to worry about calling this function on each one separately. Is there any way that I can intercept everything?
I've tried using Reflection.Emit to create a wrapping provider and using reflection to replace it on the data context and it turns out that even with Reflection.Emit I can't implement the internal IProvider interface.
I've also tried replacing the provider with a RealProxy based class and that works for non-compiled queries, but the CompiledQuery.Execute method is throwing an exception because it won't cast to the SqlProvider class. I tried replacing the response to the Compile method on the provider with another proxy so I could intercept the Execute call, but that failed a check on the return type being correct.
I'm open to any other ideas or ways of using what I've already tried?
It's hard to tell whether this is an applicable solution without seeing your code, but if you have a DI-friendly app architecture you can implement an interceptor and have your favorite IoC container emit the appropriate type for you, at run-time.
Esoteric? A little. Consider an interface like this:
public interface ISomeService
{
IEnumerable<SomeEntity> GetSomeEntities();
// ...
}
This interface might be implemented like this:
public class SomeService : ISomeService
{
private readonly DbContext _context // this is a dependency!
private readonly IQueryTweaker _tweaker; // this is a dependency!
public SomeService(DbContext context, IQueryTweaker tweaker) // this is constructor injection!
{
_context = context;
_tweaker = tweaker;
}
public IEnumerable<SomeEntity> GetSomeEntities()
{
return _tweaker.TweakTheQuery(_context.SomeEntities).ToList();
}
}
Every time you implement a method of the ISomeService interface, there's always a call to _tweaker.TweakTheQuery() that wraps the IQueryable, and that not only gets boring, it also feels like something is missing a feature - the same feeling you'd get by wrapping every one of these calls inside a try/catch block, or if you're familiar with MVVM in WPF, by raising this annoying PropertyChanged event for every single property setter in your ViewModel.
With DI Interception, you factor this requirement out of your "normal" code and into an "interceptor": you basically tell the IoC container that instead of binding ISomeService directly to the SomeService implementation, you're going to be decorating it with an interceptor, and emit another type, perhaps SomeInterceptedService (the name is irrelevant, the actual type only exists at run-time) which "injects" the desired behavior into the desired methods. Simple? Not exactly.
If you haven't designed your code with DI in mind (are your dependencies "injected" into your classes' constructor?), it could mean a major refactoring.
The first step breaks your code: remove the IQueryTweaker dependency and all the TweakTheQuery calls from all ISomeService implementations, to make them look like this - notice the virtualness of the method to be intercepted:
public class SomeService : ISomeService
{
private readonly DbContext _context
public SomeService(DbContext context)
{
_context = context;
}
public virtual IEnumerable<SomeEntity> GetSomeEntities()
{
return _context.SomeEntities.ToList();
}
}
The next step is to configure the IoC container so that it knows to inject the SomeService implementation whenever a type's constructor requires an ISomeService:
_kernel.Bind<ISomeService>().To<SomeService>();
At that point you're ready to configure the interception - if using Ninject this could help.
But before jumping into that rabbit's hole you should read this article which shows how decorator and interceptor are related.
The key point is, you're not intercepting anything that's internal to LINQ to SQL or the .NET framework itself - you're intercepting your own method calls, wrapping them with your own code, and with a little bit of help from any decent IoC container, you'll be intercepting the calls to methods that call upon Linq to SQL, rather than the direct calls to Linq to SQL itself. Essentially the IQueryTweaker dependency becomes a dependency of your interceptor class, and you'll only code its usage once.
An interesting thing about DI interception, is that interceptors can be combined, so you can have a ExecutionTimerServiceInterceptor on top of a AuditServiceInterceptor, on top of a CircuitBreakerServiceInterceptor... and the best part is that you can configure your IoC container so that you can completely forget it exists and, as you add more service classes to the application, all you need to do is follow a naming convention you've defined and voilĂ , you've just written a service that not only accomplishes all the strictly data-related tasks you've just coded, but also a service that will disable itself for 3 minutes if the database server is down, and will remain disabled until it's back up; that service also logs all inserts, updates and deletes, and stores its execution time in a database for performance analysis. The term automagical seems appropriate.
This technique - interception - can be used to address cross-cutting concerns; another way to address those is through AOP, although some articles (and Mark Seeman's excellent Dependency Injection in .NET) clearly demonstrate how AOP frameworks are a less ideal solution over DI interception.

Questioning Dependency Injection through name-lookup

I find myself struggling with the fuzz around the concept of string-based 'Service Locators'.
For starters, IoC is great, and programming to interfaces is the way to go. But I fail to see where the big benefit lies in the yellow-pages pattern used here, apart from compilation-less reconfigurability .
Application code will use a (Spring) container to retrieve objects from. Now that's nice: since the code needs to know only the needed interface (to cast to), the Spring container interface, and the name of the needed object, a lot of coupling is removed.
public void foo(){
((MyInterface) locator.get("the/object/I/need")).callMe();
}
Where, of course, the locator can be populated with a gazillion of objects of all kind of Object derivatives.
But I'm a bit puzzled by the fact that the 'flexibility' of retrieving an object by name actually hides the dependency in a type-unsafe, lookup-unsafe manner: where my compiler used to check the presence of a requested object member, and it's type, now all of that is postponed to the runtime phase.
The simplest, functionally allright, pattern I could think of is a giant, application wide struct like object:
public class YellowPages {
public MyInterface the_object_i_need;
public YourInterface the_object_you_need;
....
}
// context population (no xml... is that bad?)
YellowPages locator = new YellowPages();
locator.the_object_i_need=new MyImpl("xyx",true),
locator.the_object_you_need=new YourImpl(1,2,3)
public void foo(){
locator.the_object_i_need.callMe(); // type-safe, lookup-safe
}
Would there be a way/pattern/framework to ask the compiler to resolve the requested object, and check whether it's type is ok? Are there DI frameworks that also do that?
Many thanks
What you are describing is an anti-pattern, plain and simple. Dependency injection (done via the constructor if possible) is the preferred way to do Inversion of Control. Older articles on IOC talk about service location as a viable way to implement the pattern, but you'd be hard pressed to find anyone advocating this in more recent writings.
You hit the nail on the head with this statement:
But I'm a bit puzzled by the fact that the 'flexibility' of retrieving
an object by name actually hides the dependency in a type-unsafe,
lookup-unsafe manner:
Most modern DI frameworks can get around the type-unsafe part, but they do hide the dependency by making it implicit instead of explicit.
Good article on this topic:
Service Locator is an Anti-Pattern
Spring is the only DI framework that I've used, so I can't speak for others, but even though Spring give you the ability to request an object by its name in your code, you don't have to get your Spring beans by name -- in fact, if you do, you're not really capitalizing on the "I" (inversion) in IOC.
The whole principle behind Spring/DI is that your objects shouldn't be asking for a particular object -- it should just have whatever objects it needs handed to it by the IOC container. The distinction is subtle, but it's there. The former approach would resemble the code that you pasted:
public void foo(){
((MyInterface) locator.get("the/object/I/need")).callMe();
}
The latter approach, by contrast, doesn't depend on any service locator, nor does it depend on the "name" of the object that it wants:
private ObjectINeed objectINeed;
public void setObjectINeed(ObjectINeed objectINeed) {
this.objectINeed = objectINeed;
}
public void foo(){
objectINeed.callMe();
}
It's the IOC container that calls the setObjectINeed() method. DI is definitely tackles the same problem as the service locator pattern, but it goes that extra step towards getting rid of the dependency on your service locator class.

Castle Windsor - Lookup Method Injection for transient instances

The short question:
Does Castle Windsor have something similar to Spring.Net's "Lookup Method Injection" that can be configured from XML, which provides the ability to fetch transient instances from the container without the class being aware of the IoC container?
The long question:
I'm a long time Spring/Spring.Net user and I have been experimenting with Castle Windsor, by trying to port a project over to it. Spring.Net has a concept of "Lookup Method Injection" which (from the Spring docs)...
Lookup method injection is the ability of the container to override methods on container managed objects, to return the result of looking up another named object in the container. The lookup typically involves a prototype object as in the scenario described in the preceding section. The Spring framework implements this method injection by a dynamically generating a subclass overriding the method using the classes in the System.Reflection.Emit namespace.
What this means is, If I had the following...
public class SomeTransient
{
// ... I have dependencies that need to be filled by IoC container
}
public class SomeClass
{
public virtual void Work()
{
var o = CreateTransient();
}
public virtual SomeTransient CreateTransient() { }
}
I can instruct Spring to override the CreateTransient method, and have that method return a new container created transient instance (with it's dependencies initialized) each time the method is called.
The unique part of this is, it doesn't require direct links to the Spring Framework (eg. SomeClass doesn't have to implement a specific interface).
Is there something similar in Castle Windsor to accomplish this via XML?
(I will eventually move away from XML config, but at the moment I'm just trying to get it running)
Castle has something better; Typed Factories.
You can also inject even a delegate!
http://stw.castleproject.org/Windsor.Typed-Factory-Facility-delegate-based-factories.ashx
It is better because it does not depend on dynamically generation code, and it looks much more cleaner.
It looks much more cleaner because the class doesn't depend on someone overriding that method. It is impossible to test this class without subclassing.
If you really want to do something like this, i would expect:
public abstract class SomeClass
{
public abstract SomeTransient CreateTransient();
}
but... again it doesn't feel right.
Edit 2
Unity 2 support these kind of delegate factories; you can read more here:
http://www.truewill.net/myblog/index.php/2010/05/06/unity_2_0_combining_injectionfactory_and
thanks to #eiximenis

Resources