Do action before spring context created - java

How can I execute the action, before Spring context created? I found only one solution that more or less can satisfy me, it is listening ApplicationStartingEvent but I don't know how correctly do it because Spring doesn't see listener bean because context not created yet. So maybe someone knows ways how to catch ApplicationStartingEvent or maybe another better solution to do it.

Interface ApplicationContextInitializer could suffice for your requirement.
Read ApplicationContextInitializer documentation
Implementing ApplicationContextInitializer allows you to do additional tasks/initializations before persistent bean definition is loaded (i.e. your application-context.xml). One such use is, when you want to select profiles before you will load definitions.

Related

Bean and Dependency Injection configuration from Database Instead XML

Currently we have all service class configuration defined in Application-Context.xml file. Application context will be initialized during the application startup with all beans defined in the context file and spring handles dependency injection.
I am looking for a solution where it has to load particular service class during run time based on specific parameter from Database.
For example, there are two classes exist in code base such as FooService1.java and FooService2.java. Each class will have dependency with appropriate DAO class such as FooDAO1.java and FooDAO2.java.
Instead of defining these in applciation-context.xml file, a run time parameter will decide which service needs to be loaded and its corresponding DAO which needs to be injected. Basically what i am trying to achieve here is DB oriented Dependency Injection to keep all application context information in database instead of XML.
Tables would look like: SERVICE_BEANS, DAO_BEANS and some intermediate table to have dependency information.
I just saw JdbcBeanDefinitionReader class in spring. Can I use this to implement DB oriented DI? I don't see much example on this. Please let me know if anyone has any examples.
I think you can generate beans # runtime and register them to spring-context.
Refer to Registering beans(prototype) at runtime in Spring
Hope that helps !

Java based dependency injection in Spring

I'm working in a webapp and this is the first time that I'm using Java based configuration. I have a bunch of class to configure all:
ApplicationContext
PersistenceContext
SecurityContext
WebAppInitializer
WebMvcContext
Now I'm defining Spring Data repositories and the service layer so I need to inject the repositories there. Normally I would use Autowired but I've read that it is preferable to define the injections manually so the question is, where?
Maybe neither of the previous configuration classes is suitable for such task but, do I have to create a single class to define all the injections or is better to have on for each function? What happens if the project grows too much?
I think that the main question would be what is best way to organize dependencies in a Spring project. What do you do?
I add here an image of the structure of the project as a petition. I'm trying to decouple layers and now I need to inject UserRepository to UserService.
No, I would not define a single class to do all the injections. All your classes are coupled that way.
I don't understand what "define the injections manually" means. You have to specify them in either XML or annotations. There's no other way that I know of.
You don't say if you're using XML or annotation configuration. I find myself using the latter more of the time, with only enough XML configuration to tell the Spring app context to scan for annotations.
The Spring idiom would have you specify your configuration in layers if you're using XML. It's a moot point for annotations, because they go into your source code.
Your application will read the Spring context on start up, instantiate all the beans, and wire together the necessary dependencies. You're good to go from then on.
I disagree with the link you provided. Avoid autowiring? No.
The article said that he recommends using XML configuration for large projects. This is a very small project at this point. It seems to me that auto wiring with annotations would be fine even by the article's author's words.

Inject settings or load once-global lookup?

Still getting the hang of good dependency injection techniques vs overkill. Thoughts appreciated.
I have an application that, when it starts up, reads settings from a file. It could be a database later, I've written the part that loads the settings in a dependency injection (Guice) way, that's not a problem. These settings don't change by normal use of the application, but in a future version I may want to allow the user to change these settings from a GUI.
Here's the actual question: how should I have the various parts of the code access these settings? Some of the settings are only important very deep in the object hierarchy, but the parent objects don't need to know about them. So I could:
Use a singleton, then lookup the appropriate settings in the constructor
Pass the different settings (or the entire settings class) down the object tree
Create factories that get loaded by the Guice module, then use Factory.get()
I'm not sure how much better #3 is than #1... or is there a better way entirely?
Note: while I am using Guice, this is more an architecture question than a "how do I use XXX framework" question. So don't be afraid to answer even if you don't know Guice.
If you use CDI you can annotate your Singleton class with "#Singleton" and just inject an object of this class into a subclass property.
Don't know how it is in Guice.
I think using a Injection mechanism to ensure only one Property instance is the best solution.
Hope I could help.

Load spring context in phases

This is one of those strange questions where people would ask - why?
So I will start with why I would like to do this and then go into the issue. I would like to have more control over how the spring context is loaded. For example, I do not want to load the domain and web-api at the same time. That would make the resources available before their dependencies are ready.
There might also be that I need to check the state of something before I can continue this process. So to say, there will be sequential order between modules/contexts. Maybe not just booting but also in shutdown.
So the issue is that I can't find any information on how to load the domain-context, then when that is finished I would check the state and lastly load the api-context. I would like to do all of this from java-code as I need to control the flow of the start up. I have basics working with SpringServlet loading the web-context. What I have not found any information on is if it is possible to load a context, wait and load another context that refers to the first one.
It might be good to know that I am not using JavaEE nor a container. I am only using embeddded Jetty with servlet and spring. So is there a way this can be done?
I'd suggest to consider following:
Read SmartLifeCycle and Phased for extension points on the order of application context life cycle management. The idea is that you have your top-level important beans implement the interfaces such that the standard application context initialization will be also handled to those beans in the order that you customize.
Break your application context XML files into smaller pieces. Use <import /> in the ones that depend on a higher/lower context.
Use depends-on attribute on your mission critical beans to ensure the dependencies.
Use InitializingBean on the ones that you need to make sure a dependency is satisfied for the current bean after it's initialized.
Consider lazy loaded beans and Lazy Proxy.
So the bean will be created only on first usage ...

How should each class in an application retrieve the Spring application context?

How should each class in an application retrieve the Spring application context? Or, stated another way, how many times should an application invoke new ClassPathXmlApplicationContext("applicationContext.xml")?
Usually a class does not need the application context, but it needs some of the objects Spring injects. And this is configured in that applicationContext.
As such an application typically calls new ClassPathXmlApplicationContext("applicationContext.xml") only once.
With dependency injection, you shouldn't have to, in general. But if your class really needs to be aware of the application context, implement the ApplicationContextAware interface. Spring will automatically call the setApplicationContext method defined in that interface to provide your class with the application context.
Note that if you're trying to gain access to filesystem resources, you should use ResourceLoaderAware. If you want access to the message source, then don't implement an interface; instead, inject a reference to the MessageSource bean.
I think you should take the advice from the answer to your other question here. Implementing ApplicationContextAware or ServletContextAware (if you are in a servlet container) is the best way to get the context.
Look up how spring handles Dependency Injection or Inversion of Control.
Once.
Actually you should let Spring do the heavy lifting and build/configure the classes rather than the other way around.
The whole idea is that all classes can be built without having to call the outside world for dependencies, which are 'magically' provided by the Spring framework.
This approach was invented to get away from the ServiceLocator pattern to which you are alluding, i.e. get a reference to an object to get the dependencies you need, ala JNDI.

Categories

Resources