Multiple profiles - spring bean injection - java

#Service
public interface DatabaseConnector {
public Model getModel();
}
#Configuration
#Profile({"!test"})
public class DatabaseConnectorT implements DatabaseConnector {
private final Model model;
#Autowired
public DatabaseConnectorT(#Value("${assemblerFile}") String assemblerFile) {
model = TDBFactory.assembleModel(assemblerFile);
}
}
I am getting the error, that this bean class cannot be instantiated and a default constructor should be given. Why should such one be required? I have two different implementations of the interface which should be loaded dependent on the active profile. Configuration should be done with annotations.

Default constructor is a constructor without parameters.
According to the error message I suppose that the class is being created via reflection.
So you must provide a way to create a class via reflection.
I assumed the value of assemblerFile in your constructor can't be determined via reflection and so the default constructor is called instead, which is not provided.

Related

Is it OK to inject value directly inside Bean function?

I was wondering how to do dependency injection in the most effective way inside my code.
I have this code:
#Configuration
public class SomeName {
#Autowired
private Other other;
#Bean
public void method() {
other.someMethod();
// some code
}
}
Can this code be changed into the following code(other will be used only inside this function)?
#Configuration
public class SomeName {
#Bean
public void method(Other other) {
other.someMethod();
// some code
}
}
You should avoid #Autowired if possible and inject using a constructor or method.
Starting with Java 9 and java modules (project jigsaw) there are some strict rules that make it harder for your framework to change the values of a private field.
What Spring is doing in the first example is essentially that - it breaks encapsulation to change the value of a private value. (There is a way to overcome this with "opens" directive in module-info..)
You are also becoming dependent on the framework you are using and your code becomes harder to test compared to when using a simple setter.
You are also not explicitly declaring that your class depends on another class since I can easily instantiate it and "Other" will be null.
Some resources:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-scanning-autodetection (search for jigsaw)
https://blog.marcnuri.com/field-injection-is-not-recommended/
PS: You are probably missing #Configuration on your class

Dependency Injection - Dagger2 - Generics

I am having problems injecting a generic type interface. Not sure how to do this or google it since I don't know the exact terms to search for. Sorry if i'm completely wrong just getting started with dagger.
Basically I have a use case class
public class LoadConversations<C extends IConversation>
extends UseCase<List<C>, LoadConversations.Type> {
private final IConversationRepository<C> messageRepository;
#Inject LoadConversations(#NonNull IConversationRepository<C> messageRepository) {
this.messageRepository = messageRepository;
}
....
public enum Type {
ALL, NEWER, OLDER
}
}
With IConversationRepository being an interface.
public interface IConversationRepository<C extends IConversation> {
Observable<List<C>> conversations(LoadConversations.Type params);
}
IConversation being a blank interface and ConversationModule where i provide the IConversationRepository.
Im having problems injecting with the following code. Am i missing something or doing something completey wrong. Thanks in advance.
Trying to provide as follows:
#Provides IConversationRepository<Conversation> provideConversationRepository(
ConversationRepository conversationRepository) {
return conversationRepository;
}
And I'm trying to inject this to my presenter as
private final LoadConversations<Conversation> loadConversations;
#Inject public ConversationListPresenter(LoadConversations<Conversation> loadConversations) {
this.loadConversations = loadConversations;
}
Implementation of ConversationRepository
public class ConversationRepository implements IConversationRepository<Conversation> {
#Override public Observable<List<Conversation>> conversations(LoadConversations.Type params) {
....
}
}
Error Log:
Error:(15, 10) error: com.rbttalk.android.data.repository.ConversationRepository cannot be provided without an #Inject constructor or from an #Provides-annotated method.
com.rbttalk.android.data.repository.ConversationRepository is injected at
com.rbttalk.android.di.module.sub_modules.ConversationModule.provideConversationRepository(conversationRepository)
com.rbttalk.android.domain.repository.IConversationRepository<com.rbttalk.android.domain.models.Conversation> is injected at
com.rbttalk.android.domain.usecase.conversation.LoadConversations.<init>(arg0, …)
com.rbttalk.android.domain.usecase.conversation.LoadConversations<com.rbttalk.android.domain.models.Conversation> is injected at
com.rbttalk.android.ui.main.conversation.ConversationListPresenter.<init>(loadConversations)
com.rbttalk.android.ui.main.conversation.ConversationListPresenter is injected at
com.rbttalk.android.ui.main.conversation.ConversationListFragment.userListPresenter
com.rbttalk.android.ui.main.conversation.ConversationListFragment is injected at
com.rbttalk.android.di.component.ConversationComponent.inject(conversationListFragment)
You're very close! The error message says it all:
com.rbttalk.android.data.repository.ConversationRepository cannot be provided without an #Inject constructor or from an #Provides-annotated method.
Note that this is not IConversationRepository; you've provided a binding for that with your #Provides method (which you can eventually consider converting to a #Binds method). However, that #Provides method has a parameter, ConversationRepository, which effectively asks Dagger to create an instance of that concrete ConversationRepository type for you. You've made that binding correctly, but now Dagger needs to instantiate ConversationRepository for you, and it simply doesn't know how.
You'll need to create an #Inject-annotated constructor for ConversationRepository using the annotation type javax.inject.Inject, even if it just looks like this:
#Inject ConversationRepository() {}
This allows Dagger to know that yes, it is safe to call that constructor. (This differs from Guice, which was willing to call a public parameterless constructor including the default constructor provided by Java.) Though you are welcome to accept injector-provided parameters in that annotated constructor (which might be nice if your repository has dependencies, because then you can keep the fields final), you may also choose to simply annotate some fields with #Inject and let the injector populate those after creation.

Java inject implementation using TypeLiteral

I have a project that provides an interface, let's call it IImplementMe, which i want to inject into my project. This interface will be implemented by various producers, so I need to inject all implementations. I am trying to use TypeLiteral for this.
Here is the code of the producer :
#Singleton
public class SomeImplementation implements IImplementMe {
private final String value;
#Inject
public SomeImplementation(final SomeOtherConfig configuration) {
this.value= configuration.getValue();
}
#Override
public String getValue() {
return value;
}
}
And in my registry class I have register(IImplementMe.class).to(SomeImplementation.class);
Then, in my project I inject it like this :
#Inject
public SomeEndpoint(final List<IImplementMe> implementations){
///
}
and i bind it like
private static class MarketDataSetTypeLiteral extends TypeLiteral<List<IImplementMe>> {
}
bind(new MarketDataSetTypeLiteral()).toRegistry();
I made sure my SomeIMplementation constructor gets called, but in my endpoint the List is empty, so no implementation is provided. I'm using guice for injection. Any ideas ?
LE: It turns out that the provided implementation is created after my endpoint class is created (at creation time it injects a reference of an empty list). Later in the lifecycle the reference is updated with the implementation, so I actually have access to it after guice does it's stuff.
I'm guessing it's due to the maven dependencies, and how guice handles the instantiations. Since the producer must have a dependency on my project, I guess it makes sense it gets instantiated last, thus causing my initial problem.
You are looking for multibindings -> https://github.com/google/guice/wiki/Multibindings
public class IImplementMeModule extends AbstractModule {
public void configure() {
Multibinder< IImplementMe > uriBinder = Multibinder.newSetBinder(binder(), IImplementMe.class);
uriBinder.addBinding().to(SomeImplementationOfIImplementMe.class);
uriBinder.addBinding().to(AnotherImplementationOfIImplementMe.class);
... // bind plugin dependencies, such as our Flickr API key
}
}
Then you can inject the set of IImplemetnMe as following
#Inject TweetPrettifier(Set<IImplemetnMe> implementations)
I would suggest you to have a look at MapBindings which allows you provide keys for each implementation and then you will be able to inject your bindings as a Map

No default constructor found; nested exception is java.lang.NoSuchMethodException with Spring MVC?

I am working with Spring MVC controller project. Below is my Controller and I have a constructor declared which I am specifically using for testing purpose.
#Controller
public class TestController {
private static KeeperClient testClient = null;
static {
// some code here
}
/**
* Added specifically for unit testing purpose.
*
* #param testClient
*/
public TestController(KeeperClient testClient) {
TestController.testClient = testClient;
}
// some method here
}
Whenever I am starting the server, I am getting below exception -
No default constructor found; nested exception is java.lang.NoSuchMethodException:
But if I remove TestController constructor then it works fine without any problem. What wrong I am doing here?
But if I add this default constructor then it starts working fine -
public TestController() {
}
Spring cannot instantiate your TestController because its only constructor requires a parameter. You can add a no-arg constructor or you add #Autowired annotation to the constructor:
#Autowired
public TestController(KeeperClient testClient) {
TestController.testClient = testClient;
}
In this case, you are explicitly telling Spring to search the application context for a KeeperClient bean and inject it when instantiating the TestControlller.
You have to define no-args or default constructor if you are creating your own constructor.
You can read why default or no argument constructor is required here:
Why default or no argument constructor is important in Java class?
In my case, spring threw this because i forgot to make an inner class static.
When you found that it doesnt help even adding a no-arg constructor, please check your modifier.
In my case I forgot to add #RequestBody annotation to the method argument:
public TestController(#RequestBody KeeperClient testClient) {
TestController.testClient = testClient;
}
If your environment is using both Guice and Spring and using the constructor #Inject, for example, with Play Framework, you will also run into this issue if you have mistakenly auto-completed the import with an incorrect choice of:
import com.google.inject.Inject;
Then you get the same missing default constructor error even though the rest of your source with #Inject looks exactly the same way as other working components in your project and compile without an error.
Correct that with:
import javax.inject.Inject;
Do not write a default constructor with construction time injection.

EJB Dependency Injection with interface

I have an interface I with method m and two concrete implementations A and B.
public interface I{
public void m();
}
public class A implements I{
public void m(){
//
}
}
public class B implements I{
public void m(){
//
}
}
I want to know when I inject I which of the two methods will be executed
#EJB
private I service;
///
service.m();
/////
None of them, it will become into an error since the application server doesn't know which implementation to use. To avoid this, just provide the id of the class implementation, which by default is the same name of the class but starting with lower case:
//uncomment one of these
//#EJB(name="a")
//#EJB(name="b")
private I service;
None of them. The code will compile, but you won't be able to deploy it on your application server. Without specifing type of injected class, you will get an Exception similar to this:
org.jboss.weld.exceptions.DeploymentException:WELD-001409 Ambiguous dependencies
for type [...] with qualifiers [...] at injection point [...]. Possible dependencies
[...] with qualifiers [...], Managed Bean [...] with qualifiers [...]
Container (i.e. your application server) won't be able to recognize which field do you really want to inject (A or B). It cannot just guess it out of thin air. To avoid this kind of errors, provide it with annotation (called qualifier) specifying whether you want to inject class A or class B. If you want an example, you should see this article.

Categories