what is the difference between using or not Spring Beans? - java

Probably i'll get a lot of downvotes, but it's so confusing for me all this fact of whether use beans or not. Lets suppose this example
interface ICurrency {
String getSymbol();
}
public class CurrencyProcessor {
private ICurrency currency ;
public CurrencyProcessor(ICurrency currency) {
this.currency = currency;
}
public void doOperation(){
String symbol = currency.getSymbol();
System.out.println("Doing process with " + symbol + " currency");
// Some process...
}
}
So, to inject the ICurrency impl injection i think that i can do it by two ways:
Way 1: Without Spring beans
public class CurrencyOperator {
private ICurrency currency ;
private CurrencyProcessor processor;
public void operateDefault(){
currency = new USDollarCurrency();
processor = new CurrencyProcessor(currency)
this.processor.doOperation();
}
}
Where USDollarCurrency is an ICurrency interface implementation
Way 2: Using Spring beans
#ContextConfiguration(classes = CurrencyConfig.class)
public class CurrencyOperator {
#Autowired private ICurrency currency ;
#Autowired private CurrencyProcessor processor;
public void operateDefault(){
this.processor.doOperation();
}
}
#Configuration
public class CurrencyConfig {
#Bean
public CurrencyProcessor currencyProcessor() {
return new CurrencyProcessor(currency());
}
#Bean
public ICurrency currency() {
return new USDollarCurrency();
}
I really don't understand what would be the benefits of using Spring's beans. I read some things but what i most found was about the benefits of using DI, and as i understand, both ways are injecting the dependency that CurrencyProcessor require, what is changing is the way that i am creating and using objets, am i wrong? So in concrete, my questions are:
1. What are the benefits of using Beans at this case?
2. Why should i use Spring instead of doing it manually like first way?
3. Talking about performance, which of this cases is better?

Suppose you have 2 DAO classes one for Oracle, the seconde for MySQL, and both classes are implementing a DAO interface. You define an implementation as a bean in Spring configuration file. In the business class you have an attribut of type DAO, while in the spring configuration file you choose the real type wheather Oracle or MySQL to inject or using spring annotation #Autowired
This reduce coupling and it will be easy to move from Oracle to MySQL.
#Service
public class Business {
#Autowired
private Dao daoImpl;
//Business methods that invoks Dao methods
}
In the Spring configuration file (XML file) you use the following:
<bean id="daoImpl" class="app.com.MySQLDaoImpl OR app.com.OracleDaoImpl"/>
By just changing the class attribut of your bean you change the whole implementation, without any change in your business class ! Good luck.

Your example without Spring doesn't dependency injection!
With dependency injection, the actual implementation of the interface is determined outside the code itself in order to reduce the coupling!
You should be able to need another implementation (you could for example switch from one JMS client to another...).
To answer to your last question, using Spring is (a very little bit) less performant but much more flexible.
EDIT :
Spring is not the only tool that can be used for DI but it is the most popular and it contains a lot of features. Note that many Java standards also (such as JPA) use DI.

Related

Spring Boot #ConfigurationProperties correct usage

We are actually using Spring Boot's #ConfigurationProperties as basically a configuration mapper : it provides us an easy shortcut to map properties on objects.
#ConfigurationProperties("my.service")
public class MyService {
private String filePrefix;
private Boolean coefficient;
private Date beginDate;
// getters/setters mandatory at the time of writing
public void doBusinessStuff() {
// ...
}
}
Although this was a nice productivity boost when we were prototyping the app, we came to question if this was right usage.
I mean, configuration properties have a different status in Spring Boot's context, they're exposed through actuator endpoints, they can be used to trigger conditional beans, and seem more oriented toward technical configuration properties.
Question : Is it "correct" to use this mechanism on any business property/value, or is it plain misuse ?
Any potential drawback we missed ?
Right now our only concern is that we cannot use #ConfigurationProperties on immutable classes, which is closely related to this issue on Spring Boot's tracker : Allow field based #ConfigurationProperties binding
If your property represents something that is configurable based on the environment/profile that is what the mechanism is there for. Though I'm a little unclear what you mean by
"map properities on objects".
I would not favor this style in general, especially if your bean has multiple properties to set. A more standard idiom is to have a class that encapsulates the properties/settings used to create your bean:
#ConfigurationProperties("my.service")
public class MyServiceProperties {
private String filePrefix;
private Boolean coefficient;
private Date beginDate;
// getters/setters mandatory at the time of writing
}
then your Service class would look like this:
#EnableConfigurationProperties(MyServiceProperties.class)
public class MyService {
#Autowired
private MyServiceProperties properties;
//do stuff with properties
public void doBusinessStuff() {
// ...
}
}
This would at least allow you to pass the properties easily into an immutable class through it's constructor (make copies of any mutable properties). Also having the properties bean can be reused if you find other parts of your app need some shared configuration.

What is the improvement of using DAO in Java SE?

My project manager wants me to use DAO/DTO objects to access and retrieve data from database. Project is written in Java SE without using any framework or ORM. His arguments is to make code more testable and to improve code design. Does it make sense?
How about initializing DAO object? Should it be initialized when the instance of class having DAO field is created:
private PersonDao personDao = new PersonDaoImpl();
or rather initialized when it is necessary?
public class A {
private PersonDao person;
public List<Person> findAll() {
person = new PersonDaoImpl();
return person.getAll();
}
}
It allows to mock this interface easily, but is it right to the DAO pattern usage convention?
The Data Access Object is basically an object or an interface that provides access to an underlying database or any other persistence storage.
That definition from: http://en.wikipedia.org/wiki/Data_access_object
Maybe a simple example can help you understand the concept:
Let's say we have an entity to represent an employee:
public class Employee {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The employee entities will be persisted into a corresponding Employee table in a database. A simple DAO interface to handle the database operation required to manipulate an employee entity will be like:
interface EmployeeDAO {
List<Employee> findAll();
List<Employee> findById();
List<Employee> findByName();
boolean insertEmployee(Employee employee);
boolean updateEmployee(Employee employee);
boolean deleteEmployee(Employee employee);
}
Next we have to provide a concrete implementation for that interface to deal with SQL server, and another to deal with flat files, etc...
Hope that helps
To maximimze the benefits of testability and separation of concerns you should introduce the concept of Inversion of Control (IoC). When applying IoC to the management of object lifecycles the term Dependency Injection is used. What this means is that your class A should be completely agnostic of which implementation is instantiated when.
In order to achieve this you need an extra component to bootstrap your application and inject all classes with the correct implementations.
You could set up your dependency-receiving class like this (setter injection, you can also use constructors)
public class PersonServiceImpl implements PersonService {
private PersonDao personDao;
public List<Person> findAll() {
return personDao.getAll();
}
public setPersonDaoA(PersonDao personDao) {
this.personDao = personDao;
}
}
And a component to do the dependency injection:
public class ApplicationContext {
private PersonService personService;
private PersonDao personDao ;
public PersonService getPersonService() {
if (personService == null) {
personService= new PersonServiceImpl();
personService.setPersonDao(getPersonDao());
}
return personService;
}
public PersonDao getPersonDao() {
if (personDao == null) {
personDao = new PersonDaoIml();
}
return personDao ;
}
}
Then application startup would involve this:
public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ApplicationContext();
PersonService personService = ctx.getPersonService();
personService.findAll();
}
}
As you can see, the ApplicationContext encapsulates knowlegde about:
which implementations to use
in which order to set a chain of dependencies
which dependencies are already instantiated or not
The PersonServiceImpl class is now completely testable and all concerns regarding object lifecycle management have been extracted from it.
In real life this if often done using a framework like Spring or CDI (which is becoming more and more popular recently). But in your situation, starting off with an approach like above might be a good first step. It will reap the immediate benefits mentioned by your project manager without incurring the overhead of introducing Spring, possibly changing your build too and having to learn how that works (e.g. with an XML context, source code context and/or annotations).
Introducing Spring at a later stage will be easy because all classes are already prepared for Dependency Injection. Just keep in mind that your factory (ApplicationContext in my example) should not take on any extra responsibilities like configuration management.
Also keep in mind that the above example of ApplicationContext is not a singleton. You yourself should make sure only one instance of it is created when your application starts, and all injections are handled by it. Creating duplicate instances could cause confusing bugs.
The DAO pattern is not an "enterprise" pattern. It's mostly seen in "enterprise" applications, but you can absolutely use in a an application written in SE only.
It's not because you're writing an SE application that you don't have to test, so indeed, your code will be more testable using the DAO pattern and IOC rather than using straight JDBC in your application.
The way you're implementing your class using the DAO is problematic because your class cannot be tested properly because of the tight coupling between your class A and your DAO implementation. You're better off using the IOC pattern as well with a framework like Guice or Dagger (both designed with SE in mind).
For a code example, look at slnowak's answer.
The way you are using it, it is still tightly coupled with your class A.
You should provide your DAO as a dependency, using constructor or setter. Probably the most preferable way is to use some kind of Inversion of Control (for example dependency injection framework).
Your class A should be something like:
public class A {
private PersonDao personDao;
// possibly an #Inject annotation
public A(PersonDao personDao) {
this.personDao = personDao;
}
public List<Person> findAll() {
return personDao.getAll();
}
}
And actually, I would consider it an antipattern this way. It depends on how you are about to use your class A.
If it contains different business logic - fine.
If it just dispatches a call to DAO (I don't like this name, maybe use Repository instead ;)) then it is just unnecessary layer of abstraction.
Another thing - you mentioned DTO. So a Person class is just a DTO in this case? Here we could have another antipattern. DTO is fine for example if you need to transform your business object(s) into something that is visible on the screen. Or to separate perstistence model from business model.
What I'm trying to say is: don't make a Person class just a data structure. Give it some behaviour.

Autowiring in classes without RequestMapping

I am working on three different tables. I am using Hibernate to query these tables. I implemented successfully the DAO and the service layers, but i have few problems with the controller package. Here is my code, my controller package contains 3 classes , each should handle a table (i have 3 tables as i said before).
#Controller
public class Ods_Gis_Actel_Controller {
Param_Gis_Actel_Controller Param = new Param_Gis_Actel_Controller();
Tbl_Dim_Actel_Controller Dim = new Tbl_Dim_Actel_Controller();
#Autowired
Ods_Gis_Actel_metier service;
#RequestMapping(value="/index")
public String pageIndex(Model model)
{
addOdsTable(model);
Param.addParamTable(model);
Dim.addDimTable(model);
return "Affichage";
}
public void addOdsTable(Model model)
{
model.addAttribute("listeOds",service.getAll());
}
}
#Controller
public class Param_Gis_Actel_Controller {
#Autowired
Param_Gis_Actel_metier service;
public void addParamTable(Model model)
{
model.addAttribute("listeParam",service.getAll());
}
}
#Controller
public class Tbl_Dim_Actel_Controller {
#Autowired
Tbl_Dim_Actel_metier service;
public void addDimTable(Model model)
{
model.addAttribute("listeDim",service.getAll());
}
}
The request mapping is done in the 1st class, whose method calls 2 other methods from the other classes. But it seems, that the autowiring works only in the class, where the RequestMapping is performed.
Is this true?
how can i use the other methods from the classes which don't contain the RequestMapping if the autowiring doesn't work for them?
I gone through your problem , I think you are not so much aware the objective of #Controller , #RequestMapping . So First of all you need to know , why we use #Controller?, this is used to give business logic to your request. When request is hited from user , then your DispatcherServlet match the url from your request to value of RequestMapping annotation of all defined controller. And according to that , the matched mapping method is called and further procees done by framework. Now come to #Autowire, this is used to load the bean class definition from the xml configuration. So the #Autowire and #RequestMapping having different objective . So it's wrong to say here that the
**autowiring** works only in the class where the RequestMapping is performed.
Now your second question , How you can use simple class? there are two ways to achieve that as far as I know,
1) To create the Object of that class inside your class as you done in your code
2) To create the instance of that class using factory-method.
for the second point , you have to first define your class inside the configuration file by following the below format
<bean id="paramGis" class="<whatever_package_detail>.Param_Gis_Actel_Controller" factory-method="createInstance"/>
here one things you have to care that this method should be static .
and your class would look like that
#Service
public class Param_Gis_Actel_Controller {
private static Param_Gis_Actel_Controller paramGis;
public static Param_Gis_Actel_Controller createInstance(){
if(paramGis==null){
return new Param_Gis_Actel_Controller();
}
return paramGis;
}
public void addParamTable(Model model)
{
model.addAttribute("listeParam",service.getAll());
}
}
If you are still getting problem let me know.
I think you are having difficulties with the Java/Spring way. We don't use #Controller/#Autowired like that.
It's kind of hard to explain shortly (I strongly recommend you read the official document for that), but in short, you shouldn't create a Controller object inside another controller. The objects with annotation marks (#Controller, #Service...) should be generated and managed by Spring. At initiation time they will be injected with the #Autowired services by "Spring" way. Of courses you can intervene into that process, but by other special methods.
P/s: your naming convention is not for Java ;). If you create a program for personal use it maybe ok, but you will have difficult times collaborating with other Java developers.
Through method name as default one for access that particular method or use #Qualifier annotations.

Strategy for many DAOs in Spring Java

We have many DAOs in an existing project (currently with no interfaces, but that can change). Rather than wiring a Spring-managed bean for each DAO class and injecting them into the service layer, we have a DAO "factory" of sorts that looks like this:
public class DAOFactory {
private static DAOFactory daoFac;
static{
daoFac = new DAOFactory();
}
private DAOFactory(){}
public static DAOFactory getInstance(){
return daoFac;
}
public MyDAO1 getMyDAO1(){
return new MyDAO1();
}
public MyDAO2 getMyDAO2(){
return new MyDAO2();
}
...
(Note that MyDAO1 and MyDAO2 are concrete classes)
This allows us to easily add/call DAO methods within the Service layer, without having to 1.) add a DAO interface as a property to the service class 2.) wire the DAO implementation into service method via configuration. (And we sometimes use multiple DAOs in one service class).
DAOFactory.getInstance().getMyDAO1().doSomething();
This strategy has worked for us so far (we haven't had much need for switching implementations), but I'm wondering if there is a better method if we were able to start new? I looked at autowiring the DAOs as beans, but I'd still need to create properties in each service class to represent those DAOs being used. And in a large project, I'm hesitant to start auto-wiring beans anyway - we need to provide visibility for all developers.
It feels like I'm flip-flopping between a.) being tightly-coupled to an implementation, but less code/config overhead and b.) being loosely coupled to interfaces, but requiring plenty of code/configuration overhead.
Is there a better way I'm missing? Something in-between? Opinions welcomed.
I will have all the DAO s as Spring managed components and inject them into services for loose coupling. Why do you think autowiring beans is bad in a big project.?
Just annotate each DAO class with #Component
and replace MyDao mydao = factory.getmyDao() with
#Autowired
MyDao myDao;
I dont see much coding/configuration overhead with it.
I've taken a couple of different approaches so far with my projects, and haven't really settled on what's "best." And there may not be a "best" but perhaps a "best for your needs."
First, I went with a base service class.
public abstract BaseService {
#Autowired FooDAO fooDao;
#Autowired BarDAO barDao;
. . .
. . .
protected getFooDAO() {
return this.fooDao;
}
}
Then in my service classes, I can write simply
Foo foo = getFooDAO().uniqueById(id);
This works, and it keeps my services tidy from all the autowiring and accessor classes for the dao instance variables. Problem is, I've now got a copy of this base class in each of my services, which frankly, meh, not that big of a deal. But it also sort of produces a code smell because it's not using composition over inheritance where, in essence, a reason for DI is to encourage composition.
A coworker suggested a factory such as yours, and called it ServiceProvider. We autowire this into our services.
#Component
public class ServiceProvider {
#Autowired FooDAO fooDao;
public FooDAO getFooDAO() {
return this.fooDao;
}
. . .
// yadda yadda
}
Then we have something like what you have:
Foo foo = getServiceProvider().getFooDAO().uniqueById(id);
And that's pretty darned ugly and really doesn't lend itself to clarity. So, we've dabbled with using just the instance of the provider, and naming it something short and sweet like sp. Then we get
Foo foo = this.sp.getFooDAO().uniqueById(id);
And again, it works. And it's probably a better design. And we only autowire the DAOs in one place, rather than into each Service, even though that's not really much of a problem either way. But it makes me feel better even though Me Feeling Better isn't a project requirement (but don't cha think it oughta be?)
I've been thinking we'd combine the two. We'd change BaseService to autowire the ServiceProvider, and then wrap the ugly calls.
public abstract BaseService {
#Autowired ServiceProvider serviceProvider;
protected getFooDAO() {
return this.serviceProvider.getFooDAO();
}
protected getBarDAO() {
return this.serviceProvider.getBarDAO();
}
}
Makes for nicer shorthand in my services, doesn't require me to autowire each DAO into each service which just gets clunky, in my opinion, but also doesn't have a copy of all those references in each service which, you know, is an utterly ridiculous concern.
The problem that I'm left with is stepping through code in the debugger. Stepping in and out of each of those getWhateverDAO() calls is tedious, and adding a possible step through getServiceProvider() doesn't help things either.
But that's where I'm at with this issue. Frankly, I think I spend so much time thinking about this because it's a great way of avoiding all the truly hard problems our application poses.
Good question.
I think that is is very pity that you started to use DAOFactory. Spring is a super flexible factory, so I really do not understand why do you need other one. Autowiring in spring has a lot of advantages and do not reqire interfaces, so you can easily switch to using spring to access DAOs. IMHO it does not reduce but improves the visibility for other developers.
Moreover if you are thinking about refactoring of DAO layer take a look on GenericDAO from google code: http://code.google.com/p/hibernate-generic-dao/
I had a very good experience with this library. It saves your time. You actually do not need many DAOs. You need exactly one DAO. You obviously can wrap the generic DAO from google code and add your application specific terminology and functionality. But do not add entity specific code there. The entity specific code should be at service layer. No more fragile HQL, no coupling with hibernate if you are using Hibernate criteria API. This library supports both Hibernate and JPA and its API is very simple and strong.
If you use too many DAOs in 1 service you should think about to split 1 service into more lower lever (fine grained) services
If you don't want to annotate your DAO classes or have configuration annotations like #Value polluting them, I see two options:
1. Create a #Configuration with DAO #Beans
#Configuration
public class DaoConfiguration {
#Value("${db.name}")
private String dbName;
#Value("${foo.table}")
private String fooTable;
#Value("${bar.table}")
private String barTable;
#Bean
private FooDao fooDao() {
return new FooDao(dbName, fooTable);
}
#Bean
private BarDao barDao() {
return new BarDao(dbName, barTable);
}
}
Then create an #Autowired field for the DAO you need:
#Autowired
private FooDao fooDao;
2. Create a DAO factory #Component
Useful if you need to do some cleanup when the DAOs are destroyed.
#Component
public class DaoFactory {
#Value("${db.name}")
private String dbName;
#Value("${foo.table}")
private String fooTable;
#Value("${bar.table}")
private String barTable;
private FooDao fooDao;
private BarDao barDao;
#PostConstruct
public void init() {
fooDao = new FooDao(dbName, fooTable);
barDao = new BarDao(dbName, barTable);
}
#PreDestroy
public void destroy() {
try {
fooDao.close();
} catch (Exception e) {
log.error("Failed to clean up FooDao", e);
}
try {
barDao.close();
} catch (Exception e) {
log.error("Failed to clean up BarDao", e);
}
}
public FooDao fooDao() {
return fooDao;
}
public BarDao barDao() {
return barDao;
}
}
Then create an #Autowired field for the factory in the classes you need DAOs:
#Autowired
private DaoFactory daoFactory;
And use it as:
daoFactory.barDao().findAll();

Inversion of Control, Dependency Injection and Strategy Pattern with examples in java

I am often confused by these three terms. These three look similar to me. Can someone please explain them to me clearly, with examples.
I have seen similar posts and don't understand completely.
Dependency Injection refers to the pattern of telling a class what its dependencies will be, rather than requiring the class to know where to find all of its dependencies.
So, for example, you go from this:
public class UserFetcher {
private final DbConnection conn =
new DbConnection("10.167.1.25", "username", "password");
public List<User> getUsers() {
return conn.fetch(...);
}
}
to something like this:
public class UserFetcher {
private final DbConnection conn;
public UserFetcher(DbConnection conn) {
this.conn = conn;
}
public List<User> getUsers() {
return conn.fetch(...);
}
}
This reduces coupling in the code, which is especially useful if you want to unit test UserFetcher. Now, instead of UserFetcher always running against a database found at 10.167.1.25, you can pass in a DbConnection to a test database. Or, even more useful in a fast test, you can pass in an implementation or subclass of DbConnection that doesn't even connect to a database, it just discards the requests!
However, this sort of primitive dependency injection makes wiring (providing an object with its dependencies) more difficult, because you've replaced accessing the dependency using a global variable (or a locally instantiated object) with passing the dependency around through the whole object graph.
Think of a case where UserFetcher is a dependency of AccountManager, which is a dependency of AdminConsole. Then AdminConsole needs to pass the DbConnection instance to AccountManager, and AccountManager needs to pass it to UserFetcher...even if neither AdminConsole nor AccountManager need to use the DbConnection directly!
An inversion of control container (Spring, Guice, etc) aims to make dependency injection easier by automatically wiring (providing) the dependencies. To do this, you tell your IoC container once how to provide an object (in Spring, this is called a bean) and whenever another object asks for that dependency, it will be provided by the container.
So our last example might look like this with Guice, if we used constructor injection:
public class UserFetcher {
private final DbConnection conn;
#Inject //or #Autowired for Spring
public UserFetcher(DbConnection conn) {
this.conn = conn;
}
public List<User> getUsers() {
return conn.fetch(...);
}
}
And we have to configure the IoC container. In Guice this is done via an implementation of Module; in Spring you configure an application context, often through XML.
public class MyGuiceModule extends AbstractModule {
#Override
public void configure() {
bind(DbConnection.class).toInstance(
new DbConnection("localhost", "username", "password"));
}
}
Now when UserFetcher is constructed by Guice or Spring, the DbConnection is automatically provided.
Guice has a really good Wiki article on the motivation behind dependency injection, and further using an IoC container. It's worth reading all the way through.
The strategy pattern is just a special case of dependency injection, where you inject logic instead of an object (even though in Java, the logic will be encapsulated in an object). It's a way of decoupling independent business logic.
For example, you might have code like this:
public Currency computeTotal(List<Product> products) {
Currency beforeTax = computeBeforeTax(products);
Currency afterTax = beforeTax.times(1.10);
}
But what if you wanted to extend this code to a new jurisdiction, with a different sales tax scheme? You could inject the logic to compute the tax, like this:
public interface TaxScheme {
public Currency applyTax(Currency beforeTax);
}
public class TenPercentTax implements TaxScheme {
public Currency applyTax(Currency beforeTax) {
return beforeTax.times(1.10);
}
}
public Currency computeTotal(List<Product> products, TaxScheme taxScheme) {
Currency beforeTax = computeBeforeTax(products);
Currency afterTax = taxScheme.applyTax(beforeTax);
return afterTax;
}
Inversion of control means that a runtime framework wires all components together (for example Spring). Dependency injection is a form of IoC (I don't know if another form of IoC exists) (see: http://en.wikipedia.org/wiki/Inversion_of_control).
Strategy pattern is a design pattern (defined by the GoF) where the algorithm can be replaced by another (see: http://en.wikipedia.org/wiki/Strategy_pattern). This is archived by provided several implementation of a same interface. When using an IoC like Spring, if you have several implementations of an interface, and if you can switch from an implementation to another by configuration, you are using the strategy pattern.
I also recommend reading the introduction chapter of Spring's documentation, which focuses on this issue: Introduction to Spring Framework
The first few paragraphs should do.
And this also links to: Inversion of Control Containers and the Dependency Injection pattern
Which also provides a motivational view of these very important core concepts.

Categories