Adding property values to Spring beans at runtime - java

It might be a very simple question; but since I am a beginner into Spring, I cannot understand how to assign values to Spring beans at the run time.
I followed some tutorials for learning Spring and now I know how to get started with Spring. I can understand the Spring beans.xml where the bean definition is declared, I can understand some annotations which can be used instead of xml configurations. But I cannot understand how to do the following configuration.
Let's say I have a class called Student. Each student object has a name and an age.
public class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.address = address;
}
}
This is how will I write the entry in the Beans.xml file for bean configuration
<bean id="student" class="Student">
<property name="name" value="Joe"></property>
<property name="address" value="12"></property>
</bean>
I am completely okay with this setter injection. As far as I can change the property values using the xml file,I can change the properties of the student.
But let's think we need an application to register students. Using front end form of the application, we enter name and age. My question is how can we inject those name and age values to a Student bean. Now we are dealing with a running application.
I can't understand how should we change the xml to accept the user inputs(if it is the way of doing). In all the beginner tutorials I followed, I didn't find a way to handle such situations. What they teach is what I already know.
I think I am missing some lesson on this. Please guide me to solve my problem. Some example code will be much helpful for me to understand if possible.
Thank You..!

You dont find any tutorial for your problem because your usecase is not sutable for spring. In practice we dont use spring to achieve what you are trying to do. Spring is best suitable for dependency injection of classes with singleton behaviour for example service classes for which you will generally need single instance across your application.
Generally we use ORM like hibernate for the use case which you are ferering to.

Beans are not suitable for Value Objects, which is why your approach is not working.
Beans are instantiated classes that will have long running lives during the execution of your program, they are managed by Spring. This includes instances of classes that provides business logic or classes that provide program functionality, like database connections or a socket server.
Value Objects are short lived data object instances that is used by your application, which the student class seems to be. They are managed by your program code.

Related

Validation through "mixins"

I am developing a RESTful API in Spring Boot 2+, for which I need to perform several validations. Nothing really fancy, just the typical #NotNull, #NotEmpty, #Max, #Min, #Email, #Regex, #Future, etc stuff...
Except that I have beans from an API that I must use yet cannot modify. This means that I cannot annotate the fields and methods in those DTOs.
It would be great if I could create mixin-like classes or interfaces with the same structure of the real DTOs I must use in the API, on which I would happily place bean-validation's annotations.
For example, if I had the following DTOs that I couldn't modify:
public class Person {
private String name;
private String dateOfBirth;
private Address address;
// constructors, getters and setters ommited
}
public class Address {
private String street;
private String number;
private String zipCode;
// constructors, getters and setters ommited
}
I would create the following 2 interfaces that mimic their structure and annotate them as I need:
public interface PersonMixin {
#NotBlank String name();
#Past String dateOfBirth();
#Valid #NotNull Address address();
}
public interface AddressMixin {
#NotBlank String street();
#Positive int number();
#NotBlank String zipCode(); // Or maybe a custom validator
}
As you see, the name of the methods in the interfaces match the names of the properties of the bean classes. This is just one possible convention...
Then, ideally, somewhere while the app is loading (typically some #Configuration bean) I would be very happy to do something along the lines of:
ValidationMixinsSetup.addMixinFor(Person.class, PersonMixin.class);
ValidationMixinsSetup.addMixinFor(Address.class, AddressMixin.class);
Except that ValidationMixinsSetup.addMixinFor is pure fantasy, i.e. it doesn't exist.
I know that there exists a similar construct for Jackson regarding JSON serialization/deserialization. I've found it extremely useful many times.
Now, I've been looking at both Spring and Hibernate Validator's source code. But it's not a piece of cake... I've dug into ValidatorFactory, LocalValidatorFactoryBean, TraversableResolver implementations, but I haven't been able to even start a proof-of-concept. Could anyone shed some light into this? I.e. not how to implement the whole functionality, but just how and where to start. I'm after some hints regarding which are the essential classes or interfaces to extend and/or implement, which methods to override, etc.
EDIT 1: Maybe this approach is not the best one. If you think there's a better approach please let me know.
EDIT 2: As to this approach being overly complicated, too convoluted, Rube Goldberg, etc, I appreciate and respect these points of view, but I'm not asking whether validation through mixins is good or bad, convenient or inconvenient, neither why it might be like so. Validation through mixins has pros on its own and I think it could be a good approach for some valid use cases, i.e. having declarative validation instead of scripted or programmatic validation while also separating validation from the model, letting the underlying framework do the actual validation job while I only specify the constraints, etc.
Using programmatic API (as mentioned in the comment) in case of Person you could apply next mappings for your constraints:
HibernateValidatorConfiguration config = Validation.byProvider( HibernateValidator.class ).configure();
ConstraintMapping mapping = config.createConstraintMapping();
mapping.type( Person.class )
.field( "name" )
.constraint( new NotNullDef() )
.field( "number" )
.constraint( new PositiveDef() )
.field( "address" )
.constraint( new NotNullDef() )
.valid();
Validator validator = config.addMapping( mapping )
.buildValidatorFactory()
.getValidator();
And as you are using Spring - you would need to do that in one of your sping config files where you define a validator bean.

How can I achieve bean validation in Java SE 1.6

The project which I work is a simple Java SE program which is ran using public static void main method. I have a DTO bean called StudentBean:
class StudentBean {
private String firstname;
private String lastname;
private Integer id;
private Integer age;
//setters and getters
}
I have over 100k student beans stored in a java.util.ArrayList. We have set of rules for each field. For ex, firstname should not be null and empty, age cannot be negative.
How do I write java code for validating hundreds of thousands of beans against the rules we have and write the log for the beans which violates the rules?
We thought of writing custom annotations like #NotNull, #NotEmpty, #PositiveNumber and have a validator logic which validates the beans according to the annotations they have on their variables. If you find this good, please point me to online resources which I can use to implement this.
As this is Java SE project, we do not have javax.validation jar, so no scope of using this library. It would be very helpful if we can achieve it using Java SE library only.
You can have a look at hibernate validator, and how to bootstrap the validation. There are already constraints you need available out of the box.
The fact that this is Java SE project doesn't mean you can't bootstrap validation by yourself.
I would try to keep it simple and just use a method public boolean isValid () within the bean which implement your rules. This way you need no annotations and no reflection.

Simple object-to-object mapper without xml?

I'm looking for an object-to-object mapper that works without XML configurations. It should be possible to transform any simple type as well as nested lists from one object to a completely different object.
Like:
class IncomingDTO {
String firstname;
String lastname;
List<Customer> customers;
}
class Customer {
Address address;
}
class ResultDTO {
String name; //should be a combination of firstname+lastname
List<Address> addresses; //which might come from
}
I'm looking for a way to not having iterate through each of the objects and copy every single entry manually. Maybe there is a library that I can give some kind of mapping configuration that does the rest for me?
I'd prefer to do this in your Java code if possible. I'm not sure why there's a benefit to having some declaration-based solution when a code-based solution is more likely easier to read and more extensible.
If you need a framework to do this, perhaps Dozer is of use. It provides a means of identifying mappings using annotations (as well as XML)
You should have a look at apache commons beanutils http://commons.apache.org/proper/commons-beanutils/
org.apache.commons.beanutils.BeanUtils
has methods to help you like
public static void copyProperties(Object dest, Object orig)
which
Copy property values from the origin bean to the destination bean for
all cases where the property names are the same.
Take a look at Orika,
Orika is a Java Bean mapping framework that recursively copies (among other capabilities) data from one object to another. It can be very useful when developing multi-layered applications.
Orika on GitHub

Initialize JPA-like entities with JDBC

I'm implementing several DAO classes for a web project and for some reasons I have to use JDBC.
Now I'd like to return an entity like this:
public class Customer{
// instead of int userId
private User user;
// instead of int activityId
private Activity act;
// ...
}
Using JPA user and activity would be loaded easily (and automatically specifying relations between entities).
But how, using JDBC? Is there a common way to achieve this? Should I load everiting in my CustomerDAO? IS it possible to implement lazy initialization for referenced entities?
My first idea was to implement in my UserDAO:
public void initUser(Customer customer);
and in my ActivityDAO:
public void initActivity(Customer customer);
to initialize variables in customer.
Active Record route
You could do this with AspectJ ITDs and essentially make your entities into Active Record like objects.
Basically you make an Aspect that advises class that implement an interface called "HasUser" and "HasActivity". Your interfaces HasUser and HasActivity will just define getters.
You will then make Aspects that will weave in the actual implementation of getUser() and getActivity().
Your aspects will do the actual JDBC work. Although the learning curve on AspectJ is initially steep it will make your code far more elegant.
You can take a look at one of my answers on AspectJ ITD stackoverflow post.
You should also check out springs #Configurable which will autowire in your dependencies (such as your datasource or jdbc template) into non managed spring bean.
Of course the best example of to see this in action is Spring Roo. Just look at the AspectJ files it generates to get an idea (granted that roo uses JPA) of how you would use #Configurable (make sure to use the activerecord annotation).
DAO Route
If you really want to go the DAO route than you need to this:
public class Customer{
// instead of int userId
private Integer userId;
// instead of int activityId
private Integer activityId;
}
Because in the DAO pattern your entity objects are not supposed to have behavior. Your Services and/or DAO's will have to make transfer objects or which you could attach the lazy loading.
I'm not sure if there is any automated approach about this. Without ORM I usually define getters as singletons where my reference types are initialized to null by default, i.e. my fetching function would load primitives + Strings and will leave them as null. Once I need getUser(), my getter would see if this is null and if so, it would issue another select statement based on the ID of the customer.

POJO vs EJB vs EJB 3 [duplicate]

This question already has answers here:
Difference between DTO, VO, POJO, JavaBeans?
(7 answers)
Closed 7 years ago.
Does anyone have any example of what a Java Class might look like as a POJO, EJB, and EJB 3? I'm trying to understand these java technologies but am having trouble. I was hoping it would help if I could see what an implementation of all three would look like.
POJO stands for Plain-Old-Java-Object - just a normal Java class as opposed to older technologies that required changing the class in specific ways to make it work with their framework.
class MyService {
public String sayHello() { return "hello world"; }
}
As such POJOs can be used anywhere a normal class can be used. However if you want to build an enterprise application out of them you still need some framework - Spring is a good example of a framework that can work directly with POJOs.
EJB2 is no longer relevant so you can ignore it - unless you need to maintain some legacy code. To satisfy your curiosity the same example as above would require several classes and xml descriptors to make it run - it's easy to see why it became obsolete.
EJB3 is the latest standard for developing enterprise applications which replaces EJB2 and is based on concept of taking POJOs and annotating them so that they can be used in enterprise app.
#Stateless
class MyService {
public String sayHello() { return "hello world"; }
}
As you can see it's very similar to POJOs. In fact most application written for EJB3 can easily be converted to work with Spring, and usually the other way works too.
via: http://swik.net/POJO+ejb3
EJB3 entities are plain POJOs. Actually they represent the exact same concept as the Hibernate persistent entities. Their mappings are defined through JDK 5.0 annotations (an XML descriptor syntax for overriding is defined in the EJB3 specification). Annotations can be split in two categories, the logical mapping annotations (allowing you to describe the object model, the class associations, etc.) and the physical mapping annotations (describing the physical schema, tables, columns, indexes, etc). We will mix annotations from both categories in the following code examples. EJB3 annotations are in the javax.persistence.* package. Most JDK 5 compliant IDE (like Eclipse, IntelliJ IDEA and Netbeans) can autocomplete annotation interfaces and attributes for you (even without a specific "EJB3" module, since EJB3 annotations are plain JDK 5 annotations).
for the example: http://www.laliluna.de/ejb-3-tutorial-jboss.html
#Entity
#Table(name="book")
#SequenceGenerator(name = "book_sequence", sequenceName = "book_id_seq")
public class Book implements Serializable {
Entity defines that this is an entity bean. The second defines the table name. The last one defines a sequence generator.
POJO
public class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
// setter & getter for age omitted
public String toString() {
return "Person " + name;
}
}
This can be used as an EJB3 as well.
Regarding EJB2 please forget that it exists and do not invest any time on it unless you absolutely have to (e.g work on legacy code).
Even this class (#Stateless class MyService) mentioned above is similar to POJO, it is not a traditionally-definied POJO since it has dependency on the javax.ejb package. I wish this dependency was just like a soft reference (DB concept) instead of being required. This article mentioned some ideas regarding this: How to Fix Java POJO Annotations

Categories

Resources