Basically, I want to make this code work:
#Component
abstract class MyBaseClass(val myArg: MyArgClass) {
#Autowired
private lateinit var myInjectedBean: MyInjectedBean
fun useBothArgAndBean()
}
class MyConcreteClass(myArg: MyArgClass) : MyBaseClass(myArg)
val myConcreteClass = MyConcreteClass(obtainMyArgClass())
myConcreteClass.useBothArgAndBean()
So I have a base class with one argument in the constructor and another argument injected from the Spring context. Currently, such a setup is not possible because Spring tries to inject also MyArgClass from context and because there's no such bean (it's constructed manually) it fails on "no matching bean".
The question is how to make this scenario work. Note that I cannot use the factory-method solution mentioned here https://stackoverflow.com/a/58790893/13015027 because I need to directly call MyBaseClass constructor from MyConcreteClass constructor. Perhaps there's a trick on how to avoid that or how to force Spring not to try to inject into the base constructor or ...?
You have a quite confusing setup there, and I am not sure that you are fully aware how injection by Spring works. You can
either create a class on your own, using its constructor, or
you can let Spring create the class and inject everything, and you don't call the constructor.
When you call the constructor, Spring will not magically inject some parts of your class, just because it has seemingly the right annotations. The variable myInjectedBean will just be null.
If you want to have the ability to create the class on your own using the constructor, you should not use field injection, because you would obviously not have any possibility to initialize the field.
Then your classes MyBaseClass and MyConcreteClass would look like this:
abstract class MyBaseClass(
val myArg: MyArgClass,
private val myInjectedBean: MyInjectedBean
) {
fun useBothArgAndBean()
}
class MyConcreteClass(myArg: MyArgClass, myInjectedBean: MyInjectedBean) : MyBaseClass(myArg, myInjectedBean)
Now, as already suggested by #Sam, you can have myInjectedBean be injected while providing myArg manually by writing another component that can completely be created by Spring, because it will only autowire myInjectedBean while myArg is provided as argument for a factory method:
#Component
class MyFactory(val myInjectedBean: MyInjectedBean) {
fun createMyConcreteClass(myArg: MyArgClass) =
MyConcreteClass(myArg, myInjectedBean)
}
Then in a class, where you have an injected myFactory: MyFactory you can just call myFactory.createMyConcreteClass(myArg) and you obtain a new MyConcreteClass that has an injected myInjectedBean.
I think you still do need some sort of factory. It would pass both the bean and the additional arguments to the MyConcreteClass constructor, and would look like this:
#Component
class MyFactory(val myInjectedBean: MyInjectedBean) {
fun getMyConcreteClass(myArg: MyArgClass) =
MyConcreteClass(myArg, myInjectedBean)
}
If using that approach, none of the other classes except MyInjectedBean would need to be registered with Spring.
In fact, it's a little surprising to me that you currently have MyBaseClass annotated with #Component. What do you expect that to do, and does it work?
Related
I have a postgres database which stores (as a String) the relevant class to use dependent on the information coming in from the user.
e.g. user has input Name, the database has the value NameFinder() stored against this and the code needs to create an instance of NameFinder().
I was wondering if there was a way of using reflection to instantiate this class as an #Autowired component, and then call the relevant function.
I can't seem to find a guide that uses #Autowired classes so any help would be appreciated.
For autowiring to work you need the class which uses #Autowired to be a #Component (or a child like #Service ...). https://www.baeldung.com/spring-autowire
For Spring to know what to inject, you need to define a #Bean in your Configuration
https://www.baeldung.com/spring-bean
As for the reflective instantiation in the bean:
#Bean
public Name getName(Database db) {
String nameFqn = db.getConfigTable().getNameFQN();
return (Name) Class.forName(nameFqn).getConstructor().newInstance();
}
Note this uses a no-arg public constructor. FQN means fully-qualified name, i.e. com.some.pkg.NameFinder
assuming:
package com.some.pkg;
class NameFinder implements Name {
public NameFinder(){}
}
I feel like a Spring Bean should be configurable also directly from a FQN without using reflection but I don't know how. Try reading up on a BeanFactory or something similar. Usually reflection is to be avoided.
I have the following class :
class ClassWithInjectedConstructor #Inject constructor(private val simpleInjectedObject: SimpleInjectedObject) : ClassWhichThisInheritsFrom() {
override fun check(): int {
val result = simpleInjectedObject.methodToCall() // Returns an int.
return 1;
}
}
Please ignore that this function doesn't do anything except return the value on 1.
I am trying to get a handle on how the hell I work with this class, and it's injected constructor.
In my main application class (This class is java, not kotlin), I need to use the class above... and this is how I am trying to do it :
final ClassWithInjectedConstructor instance = new ClassWithInjectedInstructor();
I am aware that I need to pass something into that constructor, but how? If it is injected, do I need some fancy syntax?
Constructor injection with Dagger means that Dagger will create the object by calling the constructor and pass all the dependencies in for you. So when you call new Something() you're effectively not making use of constructor injection. You're simply creating an object.
All you really have to do is add the #Inject annotation on the constructor. That way Dagger knows about your class and if all of its dependencies can be provided Dagger can also provide that class. That's really all you need to do and when you want to use the class somewhere else you just have to request it.
If using field injection (e.g. in your Activity) you can just add an annotated field and Dagger will inject it along with all the other dependencies
#Inject lateinit var something: Something
fun onCreate(..) { activityComponent.inject(this) }
If using it in yet another class, you can just add it to the constructor...using constructor injection again...
class OtherThing #Inject constructor(val something : Something)
Or add a provision method to your component and "request" it later...
#Component interface MyComponent {
fun provideSomething : Something
}
// ...
val something : Something = myComponent.provideSomething()
If in your example SimpleInjectedObject can not be provided by Dagger, e.g. it does not use constructor injection and you did not add a #Provides annotated method that can provide it to any of your modules, you will get a build error stating that SimpleInjectedObject cannot be provided... about which you can find more information here.
I'm using 2 common packages, Immutables and
Guice. The very first thing that happens at runtime is I load setting from environment and other sources into settings into a singleton, non-Immutable config class, let's call it MyConfig, that for example, exposes a public getSettingX() method.
MyConfig myConfig = MyConfig.intialize().create();
String settingX = myConfig.getSettingX();
I have one abstract Immutable class, call it AbstractImmutable. that at instantiation needs to set a field based on the myConfig.getSettingX().
#Value.Immutable
abstract class AbstractImmutable {
abstract String getSettingX(); // Ideally set
}
Now, typically I inject MyConfig into classes using Guice, and would liket to figure a way to do this for implementations of the AbstractImmutable class (to avoid manually having to inject the MyConfig class every time I build an object--whole reason using juice to begin with, to manage my DI). However, since the concrete Immutables classes are generated at compile, it doesn't to work with the usual Guice injection annotations.
There's indication on the Immutables site of using the builder package to annotate a static factory method, but I can't seem to figure how to add this to the abstract immutable class.
Anyone have any suggestions?
To my knowledge, there is no way to do this on the generated Immutables class itself (though there may be some funny stuff you could do with #InjectAnnotation), so you may be out of luck there.
Even though you are asking under the guise of Guice, what you are asking for reminds me of the pattern that AutoFactory uses, and should be similarly applicable. In essence, take advantage of the Factory Pattern by injecting into the factory and then the factory will create the Immutable object.
For example, specifically referring to your case,
#Value.Immutable
abstract class ValueObject {
MyConfig getMyConfig();
#Value.Derived
String getSettingX() {
getMyConfig().getSettingX();
}
String getAnotherProperty();
class ValueObjectFactory {
#Inject MyConfig myConfig;
ValueObject create(String anotherProperty) {
return ImmutableValueObject.builder()
.setMyConfig(this.myConfig)
.setAnotherProperty(anotherProperty)
.build();
}
}
}
Then, in the application code, you would inject the ValueObjectFactory directly and call create on it as
class SomeApplicationClass {
#Inject ValueObjectFactory factory;
void someMethod() {
ValueObject = factory.create("myString");
// ... do something with the ValueObject
}
}
Similarly, you could define your factory as a builder, but that will be a decision you will have to make based on the number of parameters you have.
I have a Spring based Java application where a lot of classes use the following autowired interface.. they work off this interface at all places.
#Autowired
private IOperatingSystemManager m_operatingSystemManager;
Right now, there is only one implementation of the interface as follows:
#Component
public class WindowsManager implements IOperatingSystemManager
{
// Windows based shenanigans
}
And the application works as expected. Spring is happy. Everybody is happy.
Alright, not everybody...
So, I want to add another concrete implementation of IOperatingSystemManager ..
#Component
public class LinuxManager implements IOperatingSystemManager
{
// Linux based shenanigans
}
What we want is the auto wiring of IOperatingSystemManager conditionally based on a properties file setting. (say.. os=windows.. basically something that is an arbitrary string and cannot be derived from system properties etc. simply because this is a dummy example. the actual managers are not OS related.)
I don't want to change any of the classes who have autowired to the interface and are working off the interface. All I need is for Spring to look at some logic that will dictate the Autowiring of the variables and wire up the right concrete instance for:
#Autowired
IOperatingSystemManager m_operatingSystemManager
at all the gazillion places.
The documentation & web search talk about profiles, condition, bean factory, qualifiers etc.. but we don't want to use Profiles; and Qualifiers seem to be needing changes to all the interface variable annotations.
Factory methods look promising, but being new to Spring, couldn't find a crisp answer.
What is a simple and recommended way to achieve this?
Instead of scanning the WindowsManager class, create one concrete instance that implements the IOperatingSystemManager interface or another one, depending on the your logical conditions.
First, remove the #Component annotation from the WindowsManager class.
Then, create and scan this #Configuration class, which will act as a factory for your beans:
#Configuration
public class OperatingSystemManagerFactory {
#Bean
public IOperatingSystemManager getOperatingSystemManager() {
if ( /* some logic that evaluates to true if windows */ ) {
return new WindowsManager();
} else {
// Linux default option ;)
return new LinuxManager();
}
}
}
With this solution, you shouldn't need to update anyone of your classes that reference the IOperatingSystemManager interface.
I dont know which version of spring you are using but you have options for this
http://www.intertech.com/Blog/spring-4-conditional-bean-configuration/
Here, as you can see, you can create a bean based on a condition that you can decide. It actully gave your example, Windows and Linux :), so i believe thats what you are looking for.
Edit:
If you are using spring-boot, you have some other Conditional annotations
http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-auto-configuration.html#boot-features-condition-annotations
I having a Spring class, where I am autowiring a service using constructor, plus in the same constructor I am intializing other field of the same class.
#Component
class Converter {
private TestService testService;
private Interger otherFields;
#Autowired
public Converter(TestService testService) {
this.testService = testService;
this.otherFields = new Integer(10);
}
}
My Functionality is working fine, but is it a good practice?, would #Autowired annotation have any impact on otherFields intialization process
It shouldn't. Back in the xml days, when you want to pass on an argument to a constructor, you mentioned your ref bean for the constructor arg. This just means that you must have a constructor that takes the specified bean type as an argument. It doesn't really matter what you add in the constructor, as long as you are creating a valid object through the constructor (though this is just normal java programming and nothing to do with Spring).
Auto-wiring is just an easy way to create your object with the necessary dependencies and your code is still your code.
No.
When Spring is instantiating your class it will locate the constructor annotated with #Autowired, collect the beans that corresponds to the arguments the constructor takes and then invoke it with those beans as arguments.
It will then scan through all fields and methods in your class and inject beans into any fields that are annotate with #Autowired. It will not touch methods or fields that are not annotated.