This question already has answers here:
#Resource vs #Autowired
(11 answers)
Closed 6 years ago.
I have recently started using Spring framework. I'm confused between when to use #Resource vs Property argument in xml file (the traditional way). What are the special real use-cases that were considered for designing new Annotations ? Would you advice to shift completely to using Spring Annotations ?
Well the difference between #Resource and #Autowired is already well explained by a lot of posts, you could also find from my blog.
Basically they are specifying different way to search for a bean before Injection.
#Autowired will assembled by type before by name in default, whereas #Resource assembled by name in default then type. They also belong to different jar.
Regarding Property argument in xml file, it is the way you specifying the value of fields in beans. Say you want to create a bean named SamplePerson which is an object of a Person Class, what you need to do in xml is to tell Spring what the value of field in this object, just like:
Person samplePerson = new Person();
samplePerson.setAge(23);
samplePerson.setName("Rugal");
After creating such a bean, Spring context will place this object inside its container for later usage. Now you could use #Autowired or #Resource to inject this samplePerson bean into a place where needed by using
#Autowired
private Person samplePerson;
Then you will notice this person object will have its attributes corresponding to your xml definition.
But actually it is tedious to code under XML, I would rather to do all the configuration in Java style, although somebody might argue it is not dynamic enough.
Yes you could totally switch everything from XML configuration to Java configuration. You could get my sample from github.
If you are new to Spring, I will encourage you to use my archetype. You will get a fully integrated code base.
#Autowired is a Spring-specific and #Resource is JSR but current Spring supports both of them. I'd use the JSR one because it will work also without Spring framework so less changes if you decided to use something else).
Regarding the annotations vs XML please refer this question Spring annotation-based DI vs xml configuration?
It depends on use cases. For me annotations are easier because they allow to keep everything directly in the java code so it's just self-documenting. But sometimes you may want to use XML (for example if you want to change your configuration without modifying the code itself you can easily switch between different xml locations)
Related
I am working on a struts2 project that has interdependent forms.
I found struts2-conversation, stepped through their simple-example
and understood the conversation mechanism this far (please correct me if I got something wrong):
The Controller is mapped in the struts.xml
It holds the serializable ConversationContext and the Storing-Service
The ConversationContext holds POJOs mapped on forms by naming convention
Now my question is where to put the validation?
In this structure the controller is only one extending ConversationSupport and thereby ActionSupport supplying the validate, prepare and addField- & ActionError methods.
But validating within the controller would mean to validate the whole context, which does not really serve the issue.
I tried validation through annotation within the POJOs, within the context as described above which gives me some NullPointerException as if the context wasn't flushed and I think the xml-validation approach of struts2 is just too stiff. (btw how to let the generated javascripts be minified before being served? And why is there so many options?)
Mark's conversation-interceptor approach had similar problems coming up which's workarounds I didn't really get. Maybe you can help me there.
If you would like to use annotations on your model classes, it works fine with the plugin (as do the other validation approaches).
To validate your model, add #VisitorFieldValidator to the getModel() method in your controller. In the example app, you would then also add #VisitorFieldValidator to the getContact() and getPreferences() methods. Then you can use the validation annotations on the fields you wish to validate.
The service in the example is just there as a simple example of using an injected service in a Struts2 controller and how that can integrate easily with the conversation framework, but it is not directly related or needed (and I would recommend using either Spring, Guice, or CDI for dependency injection in the real world).
The ConversationContext class is intended mostly for internal use by the framework. You should be able to avoid interacting with it by using the annotations and conventions. Unless you simply wish to be adventurous.
To use XML validation in the example app, you would have to change the package name to remove the "struts2" word in order for the Struts2 resource loading tool to load the XML.
How would you extract something prior 2.5 version from .xml config? It bothers me because if #Autowired is removed from my arsenal I would not really know what to do.
Say I want to use some DAO implementation.
In service class I usually write:
#Autowired
someDaoInterface generalDao;
Then I typically call
generalDao.someInterfaceMethod(someParam param);
How would I extract implementation from config in Spring 2.0 to use this method?
Is it as dumb as just: new ApplicationContext(pathToXml) and then use .getBean or there is other way?
Why do I ask for taking bean out from configuration file?
Because in Spring MVC how can you perform your logic without getting beans out from the application context.
If you have #Controller handler then you need to make calls to the service classes' methods? So they should be somehow retrieved from the context and the only way so far is using #Autowired? Then I would also want to populate Service classes as I stated in previous example with DAO classes and they also need to be retrieved from the application context, so I would be able to write logic for service classes themself. How would people do it in the past?
I see the #Autowired as the only mean of taking something out, not because it is convenient to wire automatically - I am perfectly ok with XML.
You still have option to wire it explicitely via property or constructor parameter. (Anyway, autowired is not going to work if there is ambiguity in your container )
Of course, you can use application context and getBean() in your java code, but it violates DI pattern and makes all the spring stuff useless. Purpose of DI is to decouple your business loginc from implementation details - it's not business logic it's how and where it dependencies come from. Dependencies are just there.
By using ApplicationContext.getBean() you are breaking this pattern, and introduce dependency to:
spring itself
your configuration names
After you done this, you can as well drop use of DI and spring because you just voided all the advandages DI is providing to you. (BTW, #Autowired also introduces dependency to spring, and violates DI pattern, it also implies that there is only one instance available)
Also, answer is: in ideal case there shall be no reference to spring in your code at all.
No imports, no annotations - just interfaces of collaborating entities.
It's difficult to explain what I really want. I have an interface which has a method getRuntimeInfo() which provides me all the runtime debug information for the variables of a class. I want to see the list of all the classes that implement this interface. I am using Java and Spring.
One way I can do this is to get all the beans from the Spring Context and check using the instanceof operator. But i wouldn't want to do that for obvious performance impacts. Do i have some other option?
What about this solution:
#Component
public class WithAllMyInterfaceImpls {
#Autowire
List<MyInterface> allBeansThatImplementTheMyInterface;
}
The List is only populated once (at start up) so it should not have a significant impact in the "normal" runtime performance.
Comment:
can you explain your code
You know Spring is a IOC Container. #Component tells Spring that it should create an instance of this class (a so called Spring Managed Bean). IOC means also that the Container is responsible to inject references to other instances (Spring Managed Beans). #Autowire (as well as #Resource and #Inject -- all do the same) is such an annotation that tells Spring that this field should be populated by Spring. Spring itself tries to figure out with what instances the field should be populates. A default technique that spring uses is by type this means that Spring inspect the type of the field, and search for matching beans. In your case it is a generic List - this is a bit special. In this case Spring populate the field with an list, where the elements are all beans that match the generic type.
How about the getBeansOfType method from ApplicationContext? It returns a Map of the beans implementing your interface?
http://static.springsource.org/spring/docs/1.2.x/api/org/springframework/beans/factory/ListableBeanFactory.html#getBeansOfType(java.lang.Class)
I'm reading Spring documentation and I stumbled across a piece of text that made me ponder a bit.
You use getBean() to retrieve instances of your beans. The ApplicationContext interface has a few other methods for retrieving beans, but ideally your application code should never use them. Indeed, your application code should have no calls to the getBean() method at all, and thus no dependency on Spring APIs at all.
Well, I configured beans in my xml file. But I still need retrieve them when in need. How can I do that without getBean() method? The more detailed explanation, the better.
You need some way to retrieve Spring beans when you want to access them from classes that were not created by Spring, e.g. the main class in a command line program, and you use the getBean methods for that.
But Spring beans themselves do seldom need this feature, because it is Spring's responsibility to provide the other beans that are required, via constructor arguments or setter methods (this is the basic idea behind dependency injection).
The basic idea is "don't call us, we'll call you", meaning that your code doesn't ask Spring IOC (Inversion of Control)-container for the beans, but rather the container injects the beans into your code. The injections are configured either using xml-configuration file(s) or via annotations. For more details, see for example this and this. Also I'd recommend reading the whole chapter 3 from the reference manual (as you probably are doing).
The ApplicationContext-interface still makes it possible to ask for beans programmatically, which might be needed in some special cases, for example when integrating with some other framework or such.
Some time ago I wrote some generic parser that could handle different input file formats.
class XmlFormat extends Format {
// format stuff
// ...
}
class Parser {
Format format;
public Parser(Format format) {
this.format = format;
}
// parsing goes here
// ...
}
Next I told Spring which format description was to use.
(Disclaimer: Your Spring config may have a very different style.)
<bean id="forma1" class="com.mycompany.XmlFormat" />
<bean id="parser" class="com.mycompany.Parser">
<constructor-arg ref="format1">
</bean>
So now when I wanted Spring to give me a Parser, it injected the XmlFormat into the constructor for me.
This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
How and where are Annotations used in Java?
Java beans, annotations: What do they do? How do they help me?
Over and over, I read about Java 5's annotations being an 'advanced feature' of the language. Until recently, I haven't much used annotations (other than the usual #Override, &c), but work on a number of webservice-related projects has forced my hand. Since I learned Java pre-5, I never really took the time to sit down and grok the annotation system.
My question- do you guys actually use annotations? How helpful are they to you, day-to-day? How many StackOverflow-ers have had to write a custom annotation?
Perhaps the most useful and used case of Java Annotations is to use POJO + Annotation instead of xml configuration files
I use it a lot since (as you already stated) if you use a web framework (like spring or seam) they usually have plenty of annotations to help you.
I have recently wrote some annotations to build a custom statemachine, validations purpose and annotations of annotations (using the metadata aspect of it). And IMO they help a lot making the code cleaner, easier to understand and manage.
Current project (200KLOC), annotations I use all the time are:
#NotNull / #Nullabe
#Override
#Test
#Ignore
#ThreadSafe
#Immutable
But I haven't written yet my own annotation... Yet!
I have used annotations for:
Hibernate, so I don't need to keep those huge XML files;
XML Serialization, so I describe how the object should be rendered in the object itself;
Warning removal for warnings that I don't want to disable (and for which the particular case cannot be properly solved).
I have created annotations for:
Describe the state required in order for my method to be executed (for example, that a user must be logged in);
Mark my method as executable from a specific platform with additional properties for that platform;
And probably some other similar operations.
The annotations that I have created are read with Reflection when I need to get more information about the object I am working with. It works and it works great.
Annotations are just for frameworks and they do work great in hibernate/jpa. until you write a framework that needs some extra information from passed to it objects you wont write your own annotations.
however there is new and cool junit feature that let you write your own annotations in tests - http://blog.mycila.com/2009/11/writing-your-own-junit-extensions-using.html
I use annotations daily and they are wonderful. I use them with jsf and jpa and find them much easier to manage and work with than the alternative XML configurations.
I use annotations for describing in my state synchronisation system what classes are specialisations of the annotated classes, and the environment in which they should be used (when an object is created, it will work out for its entity lists which are the best entity classes to create for the nodes on the network; i.e., a Player entity for a server node is instead a ServerPlayer entity). Additionally, the attributes inside the classes are described and how they should be synchronised across machines.
We just used annotations to create a simple way to validate our POJO's:
#NotEmpty
#Pattern(regex = "I")
private String value;
Then we run this through the Hibernate validator which will do all our validation for us:
import org.hibernate.validator.ClassValidator;
import org.hibernate.validator.InvalidValue;
public void validate(T validateMe) {
ClassValidator<T> validator = new ClassValidator<T>((Class<T>) validateMe.getClass());
InvalidValue[] errors = validator.getInvalidValues(validateMe);
}
Works great. Nice clean code.
We use custom annotations as a part of our integration testing system:
#Artifact: Associates an integration test with an issue ID. Trace matrices are then automatically generated for our testing and regulatory departments.
#Exclude: Ignores an integration test based on the browser platform / version. Keeps the IE 6 bugs from clogging up our nightly test runs :)
#SeleniumSession: Defines test specific selenium settings for each integration test.
They are a very powerful tool, but you gotta use them carefully. Just have a look at those early .NET Enterprise class files to see what a nightmare mandatory annotations can be :)
We have a report builder as part of our webapp. A user can add a large number of widgets that are all small variations on the same set of themes (graphs, tables, etc).
The UI builds itself based on custom annotations in the widget classes. (e.g. an annotation might contain default value and valid values that would render as a dropdown. Or a flag indicating if the field is mandatory).
It has turned out be be a good way to allow devs to crank out widgets without having to touch the UI.