Is there a pattern for dynamically loadable modules in Spring Boot? - java

My Spring Boot Application features a content management system. I would like to be able to dynamically load new components without requiring an application restart. An example component may be loading a new video player component or ad component. Each component would likely contain its own controllers and views.
What would the recommended pattern be for this, and what is a good framework to help handle this? Is OSGi an option?

I'm afraid there isn't a 100% solution. There's maybe some options; let me highlight the following three:
There are Spring factories, a way to (auto-)configure your beans.
Another interesting approach to go is the way of how Spring Boot handles extensions by itself - by having its own spring-boot-starters, like in this article: https://blog.codecentric.de/en/2014/11/extending-spring-boot-five-steps-writing-spring-boot-starter/, combined with Spring Factories you could
The most plugin-like solution is the spring-plugin-project. However it looks like only loading is supported, some other features like versioning are missing, too. So you probably have to build it by yourself.
So the main problem might be in unloading and updating these things at runtime, which leads me to the final observation:
In general I have the impression that the concept of having a plugin is working a bit against the idea of Spring Boot, as it is designed for microservice architectures. So the added (plugin) functionality probably would rather be a separate microservice (with its own storage) which gets orchestrated by a gateway, here let me highlight the spring-boot-based JHipster project to show the idea of such an architecture.

Related

Dynamically loading Spring Beans and Components in Spring Boot

I'm trying to make a Spring Boot app where plugins are loaded dynamically from JARs at runtime. I also want the plugins to have access to all the Spring Boot features, most prominently Spring Data JPA. I've already figured out how to load classes from JARs, and now my problem is how to "hook up" the loaded classes (that might be Beans, JpaRepositories etc.) to "work with" my main Spring Boot application.
I also might in the future want to have my own annotation system for doing different things with the main app from the plugins, (that I know how to do using reflection) and I would want to still be able to do it after I manage to sort the Spring stuff out.
I imagine I have to tell Spring somehow to additionally look for #Components and other meaningful classes from those JARs, when it's scanning for annotations. I tried with #ComponentScan's basePackageClasses attribute but that needs to be constant, and hard-coding this is not an option for what I wanna do.
So is what I want to achieve even possible? And if it is, then can I do it through Java code, or is it maybe achievable by writing some XML configs?
When you start an spring app, beans are loaded and hooked in its contexts, so if you want to add more to it manually you might need to reload the whole context which may not be a good idea for an spring boot app.
Instead, I would suggest to use spring profiles, so you can define different configurations and based on what you want you can simple enable the one you need.
Find out more at:
https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-profiles
Hope this helps!

Vaadin7 architecture

We are currently planing our project and decided to use Vaadin. Right now we are a bit stuck figuring out how we could organize our code quite well without spending to much time. It seems MVP is a good practice for vaadin, but we are all new to the framework and it seems that quite a few people are really struggling with it. During our research we noticed that there are only very abstract tutorials and outdated frameworks. In the vaadin book also a layered architecture is recommended which we wanted to use. Our application isn't too complex (comparable to a usual businessbackend).
Is there maybe an elegant and simple solution to decouple the view,while also using the Designer?
We are also planning to use Spring Security and UI.
Thanks in advance
In my latest project I'm using Spring alongside with Vaadin and, although lots of boilerplate is added, your classes will be smaller, better organised, with single responsibility. In my case, I follow the architecture below:
Layout: class that contains the UI elements and it's design/layout.
Controller: handles all the events and user actions that a layout has. A controller only responsible of a single layout.
View: View class is the main "controller" for a specific URI fragment. If it gets too complex or with subviews, a controller class is created and injected.
Service: contains the business logic of the data. While the "Controller" handles the user interaction, the service is responsible of the business logic and data.
Repository: SpringData JPA repositories. Implement the CRUD operation and custom queries.
Model: Database entities.
Extra packages:
Event: I recommend using EventBus alongside the application.
Helpers: For that stuff that you don't know where it really fits in.
Configuration: Configuration and properties fetched from application.properties (if using SpringBoot).
Using this pattern you'll avoid ending up with spaghetti code and mixing up responsibilities on the same class. Regarding the Vaadin Designer, with this pattern it's completely independent as your layout can either be pure java or the pseudo-html.

Spring Framework - Integration with old Java webapp

I'm working on a 10-year-old Java webapp, and I would like to introduce some new technology into the project. One of the things I would like to start doing is dependency injection. I know the Spring Framework has the capability to do dependency injection, but I am having a hard time integrating the framework into the old project.
Could someone provide an example of what I would have to change in my web.xml, other files I would have to add, and other changes I would need to make? I want the smallest Spring footprint while still being bale to do dependency injection.
There are a lot of examples online about starting a new project using Spring, but I can't find any about integrating Spring into an old project.
Thanks.
You'll have to start by adding a context loader listener into your web.xml, along with the locations of the Spring configuration XML files.
You should configure the Spring DispatcherServlet to accept all URLs that you wish for it to handle.
You should write Controllers to bind and validate HTTP requests, call services, add data to ModelAndView for rendering, and map JSPs to success/failure views as needed.
You should put interfaces in front of your service and persistence tiers. Move implementations into implementation classes that Spring can inject.
Leverage Spring AOP for security and transactions and logging as needed.
Throwing new technology at a project wont make it faster\better, unless you introduce the new technology to all parts of the project. The idea behind DI is to lose dependencies between objects. The project probably is tightly coupled, so you'd have to rewrite at least parts of the thing. Depending on the size, this can be a monster to beat - ask yourself if this is worth it, if it has any positive effect on the project other than introducing new technology.
The reason why there are little to none tutorials about integrating DI container into an old project is quite simple: it usually doesn't make any sense. Either you use the pattern in all places, or none at all. The bastard child that would be creating by mixing both would be a horror to maintain. I'd really advise you think about why you want to introduce a DI container into that 10 year project. Unless there is a real good reason for doing it (and you are happy with rewriting a lot of code) don't do it.

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.

What's your "best practice" for the first Java EE Spring project? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm currently trying to get into the Java EE development with the Spring framework. As I'm new to Spring, it is hard to imaging how a good running project should start off.
Do you have any best practices, tipps or major DO NOTs for a starter? How did you start with Spring - big project or small tutorial-like applications? Which technology did you use right away: AOP, complex Hibernate...
Small tip - I've found it helpful to modularize and clearly label my Spring xml context files based on application concern. Here's an example for a web app I worked on:
MyProject / src / main / resources / spring /
datasource.xml - My single data source bean.
persistence.xml - My DAOs/Repositories. Depends on datasource.xml beans.
services.xml - Service layer implementations. These are usually the beans to which I apply transactionality using AOP. Depends on persistence.xml beans.
controllers.xml - My Spring MVC controllers. Depends on services.xml beans.
views.xml - My view implementations.
This list is neither perfect nor exhaustive, but I hope it illustrates the point. Choose whatever naming strategy and granularity works best for you.
In my (limited) experience, I've seen this approach yeild the following benefits:
Clearer architecture
Clearly named context files gives those unfamiliar with your project structure a reasonable
place to start looking for bean definitions. Can make detecting circular/unwanted dependencies a little easier.
Helps domain design
If you want to add a bean definition, but it doesn't fit well in any of your context files, perhaps there's a new concept or concern emerging? Examples:
Suppose you want to make your Service layer transactional with AOP. Do you add those bean definitions to services.xml, or put them in their own transactionPolicy.xml? Talk it over with your team. Should your transaction policy be pluggable?
Add Acegi/Spring Security beans to your controllers.xml file, or create a security.xml context file? Do you have different security requirements for different deployments/environments?
Integration testing
You can wire up a subset of your application for integration testing (ex: given the above files, to test the database you need to create only datasource.xml and persistence.xml beans).
Specifically, you can annotate an integration test class as such:
#ContextConfiguration(locations = { "/spring/datasource.xml" , "/spring/persistence.xml" })
Works well with Spring IDE's Beans Graph
Having lots of focused and well-named context files makes it easy to create custom BeansConfigSets to visualize the layers of your app using Spring IDE's Beans Graph. I've used this before to give new team members a high-level overview of our application's organization.
Focus first on the heart of Spring: Dependency Injection. Once you see all the ways that DI can be used, then start thinking about the more interesting pieces like AOP, Remoting, JDBC Templates etc. So my best bit of advice is let your use of Spring grow out from the core.
Best practice? If you're using the standard XML config, manage the size of individual files and comment them judiciously. You may think that you and others will perfectly understand your bean definitions, but in practice they're somewhat harder to come back to than plain old java code.
Good luck!
First of all Spring is about modularity and works best if one focuses on writing small components that do one thing and do it well.
If you follow best practices in general like:
Defining an interface rather than abstract classes
Making types immutable
Keep dependencies as few as possible for a single class.
Each class should do one thing and do it well. Big monolithic classes suck, they are hard to test and hard to use.
If your components are small and follow the dogmas above they should be easy to wire up and play with other stuff. The above points are naturally also true of the Spring framework itself.
PS
Dont listen to the points above, they are talking about how to do whatever. Its more important to learn how to think rather than how to do something. Humans can think, repeating something is not clever, thinking is.
I actually quite liked Spring.. It was a fresh breeze of air in your average J2EE Java Beans..
I recommend implementing the example Spring provides:
http://static.springframework.org/docs/Spring-MVC-step-by-step/
Also, I decided to go full monty and added Hibernate to my Spring application ;), because Spring provides excellent support for Hibernate... :)
I do have a DON'T however, which I learned the hard way (product in production)... If you only implement the Controller interface, and return a ModelAndView object with some data as provided with the interface, Spring does garbadge collect those resources, for tries to cache those data. So be careful to put large data in those ModelAndView objects, because they will hog up your server memory for as long as the server is in the air as soon as that page has been viewed...
Start here - I actually think it's among the best Software Dev books that I've read.
Expert Spring MVC And Web Flow
Learn the new Annotation-based configuration for MVC classes. This is part of Spring 2.5. Using Annotation-based classes is going to make writing Unit tests a heck of a lot easier. Also being able to cut down on the amount of XML is a good thing.
Oh yeah Unit Tests - if you're using Spring, you BETTER be Unit Testing. :) Write Unit tests for all of your Web and Service Layer classes.
Read up on Domain Driven Design. The fact that you can use Domain Object classes at all levels of a Spring Application means you're going to have a VERY powerful Domain Model. Leverage it.
However, when using your Domain Object classes for form population, you will want to take heed of the recent security concerns around the Spring Framework. A discussion on the Server Side reveals the way to close the hole in the comments.
A good way to get started is to concentrate on the "Springframework". The Spring portfolio has grown to a big pile of projects around various aspects of Enterprise Software. Stick to the core at the beginning and try to grasp the concepts. Download the latest binaries and check out Spring's petclinic example once you are familiar with the core. It gives quite a good overview of the various projects SpringSource has to offer.
Although the documentation is very good, I'd recommend a book after you grasp the concepts of the core. What I've found problematic with the documentation, is that it's not in depth and can't give you all the details you need.
"...Which technology did you use right away: AOP, complex Hibernate..." - I'd say a better question would be to ask what people did not use right away. I'd add the examples you cite to that list.
Spring MVC and JDBC template would be my starting recommendations. You can go a very long way just with those.
My recommendation would be to follow the Spring architectural recommendations faithfully. Use their layering ideas. Make sure that your web layer is completely detachable from the rest. You do this by letting the web tier interact with the back end only through the service layer.
If you want to reuse that service layer, a good recommendation is to expose it using Spring "contract first" web services. If you start with the XML messages that you pass back and forth, your client and server can be completely decoupled.
The IDE with the best Spring support is IntelliJ. It's worth spending a few bucks.
Whilst its been years since I have used spring, and I can't say I am a fan of it, I know that the App Fuse tool (https://java.net/projects/appfuse/) has been helpful to help people bootstrap in terms of generating all the artifacts you need to get going.
Spring is also very much about unit testing and therefore testability of your classes. That basically means thinking about modularization, separation of concerns, referencing a class through interfaces etc.
If you're just looking to dabble in it a bit and see if you like it, I recommend starting with the DAO layer, using Spring's JDBC and/or Hibernate support. This will expose you to a lot of the core concepts, but do so in a way that is easy to isolate from the rest of your app. This is the route I followed, and it was good warm-up before getting into building a full application with Spring.
With the release of Spring 2.5 and 3.0, I think one of the most important best practices to take advantage of now are the Spring annotations. Annotations for Controllers, Services, and Repositories can save you a ton of time, allow you to focus on the business logic of your app, and can potentially all you to make all of your object plain old Java objects (POJOs).

Categories

Resources