Getting right to it with a silly example:
Suppose I have created a FactoryBean implementation to create a Manager object.
public class ManagerFactory implements BeanFactory<Manager> {
// implemented methods from interface
}
Now, this factory needs to take a field called employeeId in order to look up an employee to prepopulate various fields of the Manager bean that the ManagerFactory creates (Yes, I know, in the real world Manager would extend Employee, lets pretend I can't do that).
So, since this employeeId field is not constant, is the only way to deal with this to create a setEmployeeId() method in the FactoryBean, then get the FactoryBean itself, then set the employeeId before calling getObject()?
Or am I making no sense whatsoever?
Jason
Related
I want according to role value, to get associated service, like
LogisticsUserEntity user = this.getLogisticsUserById(userId);
UserDealService userDealService = getUserDealService(user.getRole());
UserEntity userEntity = userDealService.getUserEntity(user);
LogisticsUserDao and TruckOwnerDao both implement UserDealService interface.
If role is 4, driverDao return, if it is 5, truckOwnerDao return, but I have used
#Autowired
private DriverDao driverDao;
#Autowired
private TruckOwnerDao truckOwnerDao;
I don't want to use a map, like
put(4, driverDao);
because if I want to add other dao, I have to modify the code, it violates the open-closed.
So how can I solve the extend problem?
Thanks for all your help and suggestions in advance.
As it was already mentioned in comments, you need a factory, but there are few factories.
Factory - Creates objects without exposing the instantiation logic to the client and Refers to the newly created object through a common interface. Is a simplified version of Factory Method
Factory Method - Defines an interface for creating objects, but let subclasses to decide which class to instantiate and Refers to the newly created object through a common interface.
Abstract Factory - Offers the interface for creating a family of related objects, without explicitly specifying their classes.
I would consider factory method, that way Your "user" object would have method "user.createUserDealService()" which returns needed service.
Yet I'm not sure if this should be called service, services are objects that are remote callable.
By the way it looks strange for getting userEntity based on user. Isn't user an entity already?
In my application, i'm attemping to create a many-to-many relation with additional fields
following this tutorial:
hibernate-many-to-many-example-join-table-extra-column-annotation
I would like to know what the best practice says about where to put DAO methods related to this relationship.
is it better to create a dao specific for the association (ex. StockCategoryDAO) or put the methods in the StockDAO / Category ?
For example, I get confused thinking about that:
ex.1 - a method which gives me all Stocks associated to a category...
i don't need that because i already have getter in Category model class... right?
ex.2 - i will have a page under the Stock panel, where i will select (checkboxes) which categories
are associated to this stock (the stock already exists in db).
After submit, in the controller i get all selected checkboxes (if you know an examples how to this, you are welcome) and i have to call a service method (which encapsulates my dao) to insert
the association.
In this case is it better to use the setter of Stock class, followed by a session.update(stock) or use a StockCategoryService.addCategoryService(...) for each category selected?
thanks for any advices
I would think the basic design should be "Every Model class should have its own DAO class that has all the methods defined, that operate on that particular model". This includes all getters too.
DAO methods are based on model.
So, you need to put all the getter methods for the Stock in the StockDAO class.
And you can define the RowMapper class as a inner class in the DAO class, if you are using jdbctemplate and if you want to return custom objects
I would suggest you to use JdbcTemplate class. This minimizes the code in DAO class.
Here I have listed the steps to carry out this implementation:
Declare the JdbcTemplate bean in spring.xml and inject the datasource bean as property o jdbcTemplate bean
(So during initialization itself JdbcTemplate is created with right datasurce)
Implement DAO class for every model. Define all the methods (including getters) inside the DAO class.
if your getter method returns custom object, implement rowMapper class as inner class in the DAO class.
(implementing rowMapper gives jdbcTemplate, a sense about the resultset)
I've a DAO and a service class. In the service class CapService, I've #Autowired a reference of DAO class CapDAO. The CapDAO class has a private instance field of type int, that has it's value injected from a properties file using #Value annotation.
class CapDAO {
#Value("${someProperty}")
private int expiryTime;
}
class CapService {
#Autowired
private CapDAO capDAO;
}
There is a method - retrieveCap() in the CapDAO class, which retrieves the caps from the database, based on the expiryTime. That method is invoked from another method in CapService class.
The CapService class uses the list returned from DAO method to create another object wrapping that list. And finally it returns that data structure.
Now, I'm testing a scenario using Mockito framework. I've two scenarios. In both of them, I want to invoke method of CapService class, which will get me the object. The list retrieved form database, will depend upon the value of expiryTime in the CapDAO class. And so will the content of the object returned by CapService class method.
In test, I'm invoking the method in Service class, and checking the value returned. Since DAO is reading expiryTime from properties file, both the test scenarios cannot pass with the same configured value. I've to have two differently configured DAO instance to be injected into Service class.
So, my question is - is there any way I can configure the expiryTime in CapDAO class, to create two different instance, or may be in a single instance only, and inject those in CapService based on scenario? No I don't have any setter for expiryTime. Yes, I knwo I can use reflection, but I would like to keep that as my last resort.
Short answer
reflection is easiest possibility, you can simply use ReflectionTestUtil. Note: If you have an interface which CapDAO implements, you need also AopUtils
Long answer
If you don't wanna use reflection, you need separate your context and test to get this work:
// context1.xml
<context:property-placeholder location="classpath:test1.properties"/>
// context2.xml
<context:property-placeholder location="classpath:test2.properties"/>
Then you can define someProperty with some other value in the properties.
personally i will recommend reflection.
I'm creating a set of classes to represent various data in a legacy database. Instead of using exceptions inside constructors to signal error conditions I've decided to employ factory methods to create my various objects. However, I'm trying to figure out how best to reuse some of these factories when inheriting from those classes. I'm looking for a conceptual explanation (ie: best practices state that you should do ...) not so much an actual code example (although code examples are always welcome).
For example, let's say I have a class called User with a createUser factory method. I also have another class called Employee that extends the User class. How can I reuse (ie: call) all the code in the createUser method from the createEmployee method so that it populates all of the Employees fields that are inherited from the User class?
An obvious "work around" would be to change the Employee class to have a User class instead of extending it, but that doesn't mesh with normal OO principles.
You can have an additional initializeUser(User user) method, which fills all fields. createUser creates a new User and calls initializeUser with it. createEmployer creates a new Employer and calls initializeEmployer which calls initializeUser and then adds its Employer stuff.
To make it invisible to the outside user, declare both initalize methods protected so they're only visible inside the package. Another design would be to have an own factory class which holds all create and initialize methods.
Try to find the best way to model the problem you are doing, and don't get hung up on labeling what you are doing.
For example, you want to have two classes, User and Employee, and Employee extends User.
In some class you have getUser and getEmployee.
In getEmployee you instantiate Employee, then just populate the values for the user. Here is where I think you are getting stuck on labels.
I would have a DAO (Data Access Object) class, where I put in the logic to actually go to the database. So, I have a UserDAO and EmployeeDAO.
UserDAO only knows how to populate the User object and the same with EmployeeDAO, so EmployeeDAO does something like this:
Employee getEmployee(String id) {
Employee emp = new Employee();
User u = UserDAO.getUser(id);
// either populate values or pass in the Employee since it can be a User class, to be populated.
// get employee values
return emp;
}
The code snippet helps me organize my thoughts. So, you can then either pass in the Employee instantiation and have it be populated from User or you would just copy the values over yourself.
But, this keeps the logic separated and allows you to have a more flexible design.
The way I would do that kind of thing would be something like this. I would create a polymorphic init() method for User and all the specialized subclasses of it, where necessary (for example, your Employee's init() method would only need to call the super-method). Then I'd create a separate Factory class that spits out an instance of User (the base class), be it a User or Employee or whatever. Inside its createInstance(insert params here) method, I'd create a User or Employee or your specialized instance depending on a parameter, then call the init() method for that instance you've just built. That way, you're separating the construction phase from the initialization (since every class should theoretically be able to do its own cooking at init()) and you could inherit the legacy initialization at the instance creation time if that's what you want.
Some code example:
class User() {
//... your fields and constructor here
public void init() {
//... do your User init here
}
}
class Employee extends User {
...
public void init() {
super.init();
// ... other init stuff if you want
}
}
class UserFactory{
// ...
public User createInstance(UserType type, String name, ...) {
User user;
switch (type) {
case UserType.EMPLOYEE: user = new Employee(name,...);
//... your other cases here
}
// the important part
user.init();
return user;
}
}
I have one department class.I want to create one instance department with value HR and one instance of department with value Admin, when my application loads(console app) and then i want to use those instances throughout my program.How can i use same instances everywhere in different classes?.For example i read a employee from csv file and then create a employee object.Now to create a employee object i must use the department object.I have to set proper value of department depending on the value of department read from file.How to do it
You are looking for an instance of the singleton pattern, which you can implement by declaring your constructor private and keeping a static reference variable initialized in the getter. Something like:
private static Department hr = null;
private Department() {
}
public static synchronized Department getHRInstance() {
if (null == hr) {
hr = new Department();
}
return hr;
}
from the rest of your code you can call Department.getHRDepartment() and likewise for the Admin department, which simply maps to a second static variable. (For more than 2 singletons you might want to look at using a map to store instances or using an Enum class for defining the singletons.)
A singleton instance has the drawback that dependency injection is difficult to accomplish, making building JUnit tests difficult or impossible. For most singleton patterns used it is actually better to initialise "singleton" instances while initialising your application and passing them on to the classes using them by passing them via their constructor, or by creating an object factory that passes the singleton references after creating its object instances.
Not directly an answer to your question, but your formulation makes me think that maybe what you want is an enum. If your department is a simple value, with no complex state or behaviour, it might be a good candidate for an enum.
Have a look at the enum tutorial : http://download.oracle.com/javase/tutorial/java/javaOO/enum.html
You need a Singleton. There are several ways to implement it, being the most widely known the solution posted by rsp. A nice trick is to have an enum with only one value.