Application lifecycle events with spring? - java

Establishing connections to external systems (databases etc) as part of the spring context construction seems like bad idea. Does the framework contain any method for actual application lifecycle management ? Since I'm running in embedded-mode, my best suggestion yet is to use a ListableBeanFactory to get all the beans and make an interface with start/stop/isRunning on all the application beans. Do I have to roll my own or is there something within spring I can use ?

Spring has the Lifecycle interface which you can implement. This interface provides basic start, stop and isRunning methods.
You could also implement the SmartLifecycle interface which allows for a little more control over when something is invoked due the the additional Phased interface.
See also How does Lifecycle interface work in Spring? What are "top-level singleton beans"? and Load spring context in phases.

Related

How are IoC and DI used in Spring MVC

I’m taking this udemy course all about Spring Hibernate etc. The course started with explaining how Injection of Control and dependency injection works not in a web perspective just like having simple classes or beans, defining beans and their dependencies inside a config xml file or inside the actual class Using java annotation and then a main class where the beans are created. I understood that despite not really seeing the big benefit of using IoC and DI other than separating roles like creating and maintaining objects and adding dependencies the object needs and I guess when the project is bigger this makes it cleaner and easier to follow right?
However what I don’t understand is how IOC and DI ties in a full spring MVC project. Like I understand using the #Controller annotation means it’s like an #Component and you could make it scan the components automatically when it creates beans but like unlike before there isn’t a main class where beans are created and configured rather I have a controller class where I manually create objects and models and pass that back to the views where I can use the values in the model. I don’t see how I use IoC or DI here? Or is it because it’s a simple project and perhaps the objects we created didn’t have many dependencies?Or are a lot of the uses and implementation done internally or automatically?
I am just struggling to a) see why IoC and DI are that important and b) how are they actually used in a Spring MVC project where you don’t have a main class where you do create beans.
A) Create a project, but don't add any dependency (or web-mvc). Then do it yourself then see how much need time to create configure manually. If it is just a simple mvc project, you can do it manually, but if your project increase day by day then a huge configuration file to maintain your project properly. But when you are professional developer, you don't have so much time to configure all those manually. So here is come the solution IoC and DI. Controller or other anotation are configured in build-in jars. You don't have to worried about to create controller or to create bean, just use them when you neer them. It's save your time as well as headache about is it working or not. It's increase your productivity while your are working on a big project.
B) Yes, there is no main class in web project. To run a web project, you need a server. The server first looking for a configuration (In spring, it's web.xml, dispatcher-servlet). If it available then expand the configuration file, if not then throw an error. In that configuration file, explain everything about the web project. What should do, what is not mandatory, what is entry point etc.
So, IoC and DI are very important because to understand how a web project work behind the scene or how all component work together.
IoC is a process whereby objects define their dependencies, that is, the other objects they work with, only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. The container then injects those dependencies when it creates the bean. This process is fundamentally the inverse, hence the name Inversion of Control (IoC), of the bean itself controlling the instantiation or location of its dependencies by using direct construction of classes, or a mechanism such as the Service Locator pattern.
In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Otherwise, a bean is simply one of many objects in your application.
The advantages of this architecture are:
decoupling the execution of a task from its implementation
making it easier to switch between different implementations
greater modularity of a program
greater ease in testing a program by isolating a component or mocking its dependencies and allowing components to communicate through contracts
Inversion of Control can be achieved through various mechanisms such as: Strategy design pattern, Service Locator pattern, Factory pattern, and Dependency Injection (DI).
You can go with Annotation based configuration, where you can define #Configuration class and return the required beans using #Bean annotation.
Also you can use #Component to your POJO class to treat it as Spring bean.

Spring - is using new a bad practice?

Is creating objects by hand, i.e. using new operator instead of registering Spring bean and using dependency injection considered bad practice? I mean, does Spring IoC container have to know about all objects in the application? If so, why?
You want Spring to create beans for classes that :
you want/need to inject instance(s) in other beans
you need to inject beans (or dependencies) in their own instances.
you want them to benefit from Spring features (instantiation management, transaction management, proxy classes Spring empowered such as Repository/Interceptor and so for...)
Services, controllers or interceptors are example of them.
For example a controller may need inject a service or an interceptor.
As well as you don't want to handle the instantiation of these classes by implementing yourself the singleton pattern for each one. Which could be error-prone and require boiler plate code.
So you want all of these classes to be beans managed by Spring.
But you don't want to Spring create beans for classes that :
you don't want/need to inject instance(s) in other beans
you don't need to inject beans (or rdependencies) in their own instances
you don't need them benefit from Spring features
Entity, DTO, Value Object are example of them.
For example an entity never needs to be injected into another entity or in a service as a dependency because entities are not created at the container startup but are generally created inside a method and have a scope limited to the methods lifespan.
As well as you don't need Spring to create instances which the lifespan is a method. The new operator does very well the job.
So defining them as bean instances makes no sense and appears even counter intuitive.
Spring implements the Dependency Injection pattern. You should inject in the container of spring the beans that are going to be used in other classes as dependence to be able to work. Usually classes that implement interfaces are injected so that if you change the implementation, the classes that use that interface do not know about the change.
I recommend you read the post about the dependency injection of Martin Fowler.
Using new is not bad and you are just giving the IoC container the responsibility of using new under the hood. IoC will know about all the classes that you register with it. When using frameworks, it's even more important to think about the applications architecture, because a framework makes bad design as easy to implement as good design.
If you don't need multiple implementations of a class, then use new.
If you think it's plausible that you may need to switch between implementations, consider your app design and find a suitable injection point so that refactoring won't be such a drain.
If you need multiple implementation of a class, then use a design pattern like a factory or a DI framework.
Not every nook and cranny of an application needs to be highly configurable. That's what leads to over-engineered and hard to maintain code.

Get an Guice Injector in a web application

I'm looking how I could get an Injector using Guice in a web application. I already found a solution using ServletContext, but I'm not really satisfied by this solution, because it breaks the layer architecture of the application. I'm not okay with using a ServletContext in the deeper layers of the app. Do you know another way?
An obvious solution would be to create my own singleton to host the Injector, but it seems to be that Guice should offer some out-of-the-box way to do this. I just can't find one yet...
Assuming you're using Guice Servlet and assuming the class you want the Injector in is injected itself, just inject the Injector.
Your application lifecycle is fully controlled by the servlet container, so the usage of a context listener to start the initialization process of your application is the logical result of that fact. Thus I wouldn’t say that that fact in itself is not breaking the layered architecture, just like a web request starting activity in the model layer neither breaks the layered architecture.
But in order to not break the layered architecture, the servlet context listener shouldn’t involve itself with the details of the other layers, it should only initiate the initialization. Thus all Guice related code, for example a Guice injector factory, should be located in its own layer. The role of the context listener should be limited to a call that starts the initialization (for example: MyGuiceFactory.init() or MyApp.init()).

What are pros and cons of using Spring in Swing based frontend

we have a frontend application that that uses Swing. We use Spring framework, but currently it is used just to autowire few beans...
What are reasonable next steps to use Spring more often?
Is it worth for non web application?
What would be advantages and disadvantages?
The advantages of using Spring (or any other dependency-injection) framework, is that you get a (hopefully) loosely coupled system, i.e you classes does not create instances of their collaborators, so you can easily change the implementation.
This is widely known as the Inversion-of-control principle (IoC, also the I in SOLID), and this is a good principle to follow. This means that spring is not limited to web applications, but can be used in any application that want to use an IoC-container (which is basically what spring-core is).
Disadvantages:
This really depends on how you look at things. There is more code (you have to define a entry-point for the injected collaborators), but that also makes the code more testable (the entry-points are seams which you can use to inject mocks and stubs in testing).
Also, you can't look at the code and immediately see which implementation of the collaborators that are used. But that also makes for good code, since you depend on interfaces, not implementations.
You get more config: either in an xml-file (old-style spring), or with annotations. Up until recently you had to rely on non-standard spring annotations to inject (#Autowired) resources, but now you can use the standard java dependency injection annotations, which means that you can switch out spring as your IoC-container without changing your code.
There are probably alot more advantages and disadvantages to using spring in your application, but this should get you started on deciding if using Dependency Inversion is a good thing for your application
More to the point of your question about Swing and Spring. In an application I have been working on we have been using spring to wire up the whole application. The different dialogs get their logic injected (no application logic should (in my opinion) be located together with gui logic). We are using JPA/hibernate as the database-layer, so we use spring spring to create and inject the entitymanager to our DAOs, and set up transactional settings.
I've written swing UI's that are backed by spring.
cons
the startup can be slower but you have to have a large app for that to happen.
and a splashscreen is a good idea in those situations.
its easy to "overbean" or over-zealously make everything a bean, which gets messy.
pros
spring works fine behind a GUI.
it provides a lot of services you can use
the obvious dependency injection and decoupling
a global event system, simpifying some of your own event listeners, for events that will only ever be fired by one source
resource accessing
database access is eays in 2 tier apps
rpc for 3 tier apps is easy
There are other services the spring application context provides, but that I haven't used.
If you go this direction, also look into the java-based configuration for spring, which is new in 3.0. I find that helpful as well, as it makes my spring configuration type-safe.
One disadvantage of using Spring in a Swing application is that Spring DI will make startup slower.
well one would be , if you ever decide to migrate to a web app , all you need ( well almost) to change would be the views. That's the beauty of MVC applications.

java web applicaton layout, please explain some design principles/patterns

I'm looking at this java web application that is using hibernate, jsp's, and spring framework. (from what I can tell!)
the file layout is like this:
classes/com/example/project1
inside project1
/dao
_entity_Dao.java
/dao/hibernate/
_entity_DaoHibernate.java
/factory
DaoFactory.java
DaoFactoryImpl.java
/managers
_entity_Manager.java
/managers/impl
_entity_ManagerImpl.java
/model
_entity_.java
/service
_xxxx_Service.java
/service/impl/
_xxxx_ServiceImpl.java
Have you guys read about this sort of layout somewhere? Is it considered best-practice?
What is the difference between a Factory and a Manager and a Service? (high level)
For typical layout of an application built with Spring I'd look at the example web applications that ship with it (meaning Spring).
Using things like DaoFactory is definitely not be a best-practice, the Daos should get injected instead. In general you should not need factories with Spring except for some unusual cases. Injecting is done when the web application starts up, spring reads the configuration information and constructs all the objects and plugs them in according to configuration xml and/or annotations (this is assuming singleton-scope for your objects, which is usual for stateless things like daos and services, things scoped as prototypes get new copies created as the application asks for them).
In Spring applications a service is similar to a Stateless Session Bean, it is a transactional layer encompassing application logic for a use case. So if your user takes an action that has the effect of causing several different tables to get updated you can inject the daos into that service, have a method on that service do the updates on the daos, and configure Spring to wrap that service in a proxy that makes that method transactional.
I've seen manager used as another name for what I described as service. Here I don't know what they're doing with it.
I don't like the idea of combining your interfaces and impls in one project. Just because you want to consume the interface doesn't mean you want to consume the impl and it's cumbersome transitive dependencies. The main reason is because there will be more than one impl (hypothetically, i.e. JPA/JDBC/Hibernate, or Axis2/CXF, etc.). The interfaces should not be bound to the implementation, otherwise the point is lost. This also allows for easy dependency injection as the impls simply reside on the classpath, then something like a Proxy or Spring (e.g.) can inject the implementations.
In all likelihood, all you need is a:
Interface Project
dao
EntityDao
types
Entity
HibernateImpl Project
dao
EntityHibernateDao
src/main/resources/
EntityMapping.cfg.xml

Categories

Resources