简体   繁体   中英

How many ways are there to configure the Spring framework? What are the differences between them technically? (Not pros or cons..)

I am studying this book (which I would highly recommend), and I am confused about how the authors explain the way Spring framework can be configured.

You can see some code examples that are used in the book here . (They are available to anyone..) The code I am referring the will be the code from chapter 2, if you would like to take a look.

The book states that there are 3 ways to configure the Spring Container .


XML - based configuration

This will require an xml file that resembles something like this:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" ...>

    <bean id="accountService" class="com.wiley.beginningspring.ch2.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"/>
    </bean>
    
    <bean id="accountDao" class="com.wiley.beginningspring.ch2.AccountDaoInMemoryImpl">
    </bean>

</beans>

And then in order to bootstrap Spring, the code that will be used will be:

ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("/com/wiley/beginningspring/ch2/ch2-beans.xml");

I do not have any confusions at this moment.


Java Based Configuration

In this Configuration method, there will be a class for the configuration as follows:

@Configuration
public class Ch2BeanConfiguration {

    @Bean
    public AccountService accountService() {
        AccountServiceImpl bean = new AccountServiceImpl();
        bean.setAccountDao(accountDao());
        return bean;
    }
    
    @Bean
    public AccountDao accountDao() {
        AccountDaoInMemoryImpl bean = new AccountDaoInMemoryImpl();
        return bean;
    }
}

and the code that is responsible for bootstrapping Spring looks like:

ApplicationContext applicationContext
            = new AnnotationConfigApplicationContext(Ch2BeanConfiguration.class);

So up to here, all is clear for me. (Kind of..) I would also like to note that, here we actually have an Annotation which is called @Configuration...


Annotation Based Configuration

The last configuration method available, explained in the book is the Annotation Based Configuration .

There is an xml file just like we had in the XML-Based Configuration, however a much smaller one:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" ...>
    <context:component-scan base-package="com.wiley.beginningspring.ch2"/>
</beans>

All the beans have Annotations such as:

@Component, @Service

etc..

And all the dependencies have the annotations:

@Autowired

so that beans can be injected.

The way Spring framework bootstrapped in this configuration method is as follows:

ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("/ch2-beans.xml");

Here are my questions:

Why is the (so-called) Annotation Based Configuration actually using ClassPathXmlApplicationContext but not AnnotationConfigApplicationContext above? The latter seems much more appropriate to be used in a Configuration that has the words "Annotation Based" in it, isn 't it?

The Java Based Configuration explained in the book seems like what should be called Annotation Based Configuration .?

And the way Annotation Based Configuration explained in the book actually seems to me something like: XML-Based Configuration with Autowired beans. It does not even have the @Configuration annotation, which the "Java Based Configuration" has..

How many ways are there to configure Spring framework?

To avoid confusion, we should understand, that configuration definition and bean definition are two different things . There are three ways to define configuration, available in Spring 4 by default:

  • xml-based configuration, when you describe configuration in xml file;
  • java-based configuration, when configuration is Java class, marked with specific annotations;
  • groovy-based configuration, when configuration is file with Groovy code;

And there are two ways to add bean definitions into application:

  • configuration inside bean definition, when you add beans manually by declaration right in configuration.

    In this case definition will be based on configuration type. For xml-config it will be <bean/> tag, for java-based config - method with @Bean annotation and beans {...} construction for Groovy.

  • annotation based bean definition, when you mark bean classes with specific annotations (like @Component , @Service , @Controller etc). This type of config uses classpath scanning .

In this case you have to specify directive for scanning classpath. For xml-config it will be <context:component-scan base-package="..."/> , for java-config - @ComponentScan annotation, for Groovy ctx.'component-scan'(...) invocation.

As you see, you can use configurations and bean definitions in different combinations.

Note, that if you use xml based config, you can choose approach to drive dependency injection: manually in xml, or by using annotations ( @Autowire , @Required etc). In late case you have to define <context:annotation-config/> . But do not confuse bean definition and dependency injection control.

Now based on this point of view lets try to answer your questions:

Why is the (so-called) Annotation Based Configuration actually using ClassPathXmlApplicationContext but not AnnotationConfigApplicationContext above?

Book's author mixed up concepts. Actually, this is a xml-based configuration with annotation-based bean definition.

The Java Based Configuration explained in the book seems like what should be called Annotation Based Configuration.?

You're right - Java based configuration really actively uses annotations, and could be called Annotation based. But annotation is a part of Java. In addition this is a traditional term, specified in documentation .

How many ways are there to configure Spring framework?

So, by default, we have three ways to describe configuration, and two ways to define beans. That turns six ways to configure Spring framework(by default). But, of course, all of this ways can be used in combination with each other.

The easiest way to understand this is to look into the long history of the framework how this was developed.

  • XML based configuration - this was there from the the beginning - version 1 - see javadoc for ClassPathXmlApplicationContext . This was around march 2004, the time of J2EE 1.4, which had HUGE xml configuration and Spring was big simplification (XML as well, but simpler). This uses XML for everything, including specifying autowiring, or what dependencies go where directly (your ref="accoundDao" example).

  • Annotation based configuration - in Spring 2.5 - this came as a reaction to Java EE 5, new anotations like @Autowired were introduced, there was still some context configuration in XML files - usually you would define which packages were to be scanned and rest of it was done automatically based on annotations - hence the name.

  • Java based configuration came with Spring 3, was improved in later versions. This is when AnnotationConfigApplicationContext and Configuration annotation were introduced - you could potentially drop XML entirely -> java based config. Although this became practical only later with version 4+, because of large number of xml helper tags for aop, jdbc etc.

Beside these 3 (2 actually as 1 and 2 use the same ApplicationContext class), are other ways to create a context:

At first, I want to give thanks Ken Bekov for his more resourceful answer. I have tried to improvise his answer so that anyone can learn more on this area.

Configuration Definition:

Spring 4 contains 3 ways to define its configuration. They are

在此处输入图片说明

Advantages of the annotation:

  1. All the information is in a single file (no need to open two files to configure a given behavior)

  2. When the class changes, no need to modify the xml file

  3. Annoations often said to be more intuitive and robust when re-factoring application code. Also they benefit from a better IDE guidance like guise provides. But they mix application code with DI concerns. An application gets dependent on a framework. Clear separation is almost impossible. Annotations are also limited when describing different injection behaviour at the same place (constructor, field) dependent on other circumstances (eg robot legs problem). Moreover they don't allow to treat external classes (library code) like your own source. Therefore they are considered to run faster than XML.

Advantages of xml file:

  1. Clear separation between the POJO and its behavior

  2. When you do not know which POJO is responsible for the behavior, it is easier to find that POJO (searching in a subset of files rather than all the source code)

  3. XML has the only benifit of a declarative style that is defined clearly separated from the application code itself. That stays independent from DI concerns. The downsides are verbosity , poor re-factoring robustness and a general runtime failure behaviour. There is just a general (XML) tool support with little benefit compared to IDE support for eg Java. Besides this XML comes with a performance overhead so it is usually slower than code solutions .

XML and Annotation Based Link:

  1. http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-annotation-config
  2. Annotations vs XML, advantages and disadvantages
  3. Java Dependency injection: XML or annotations
  4. Spring annotation-based DI vs xml configuration?
  5. Xml configuration versus Annotation based configuration

Groovy Based Link:

  1. https://objectpartners.com/2016/01/12/using-groovy-based-spring-configuration/
  2. http://blog.andresteingress.com/2014/02/14/grails-java-based-spring-config/

Bean Definition:

There are 2 ways to bean Definition: 在此处输入图片说明

Scanning classpath:

For xml-config it will be <context:component-scan base-package="..."/> , for java-config - @ComponentScan annotation, for Groovy ctx.'component-scan'(...) invocation.

Dependency Injection:

In xml based config, dependency injection can be done manually in xml , or by using annotations (@Autowire, @Required etc). On that case It is need to define <context:annotation-config/>

Question & Answer:

Q1: Why is the (so-called) Annotation Based Configuration actually using ClassPathXmlApplicationContext but not AnnotationConfigApplicationContext above?

Ans: It is a xml-based configuration with annotation-based bean definition.

Application Context:

  1. http://docs.spring.io/spring/docs/4.2.0.RELEASE/javadoc-api/org/springframework/context/ApplicationContext.html

AnnotationConfigApplicationContext:

1. AnnotationConfigApplicationContext and parent context

ClassPathXmlApplicationContext:

  1. http://www.tutorialspoint.com/spring/spring_applicationcontext_container.htm
  2. http://www.mkyong.com/spring3/spring-3-hello-world-example/

Q2: The Java Based Configuration explained in the book seems like what should be called Annotation Based Configuration.?

Ans: You're right on that case. Java based configuration uses annotations, and called annotation based configuration. But annotation is a single part of Java, nothing else.

But elaborately we need to understand how this hierarchy comes from xml to annotation based and at last groovy based?

An alternative to XML setups is provided by annotation-based configuration which rely on the bytecode metadata for wiring up components instead of angle-bracket declarations. Instead of using XML to describe a bean wiring, the developer moves the configuration into the component class itself by using annotations on the relevant class, method, or field declaration. As mentioned in the section called “Example: The RequiredAnnotationBeanPostProcessor” , using a BeanPostProcessor in conjunction with annotations is a common means of extending the Spring IoC container. For example, Spring 2.0 introduced the possibility of enforcing required properties with the @Required annotation.

Spring 2.5 made it possible to follow that same general approach to drive Spring's dependency injection. Essentially, the @Autowired annotation provides the same capabilities as described in Section 6.4.5, “Autowiring collaborators” but with more fine-grained control and wider applicability.

Spring 2.5 also added support for JSR-250 annotations such as @PostConstruct , and @PreDestroy .

Spring 3.0 added support for JSR-330 (Dependency Injection for Java) annotations contained in the javax.inject package such as @Inject and @Named . Details about those annotations can be found in the relevant section.

Q3: How many ways are there to configure Spring framework?

Ans:

Theoretically, 3 ways to describe configuration, and 2 ways to define beans. It turns 3*2 = 6 ways to configure Spring framework (by default). All of this ways can be used in combination with each other.

But Actually, in a single word, we can configure spring framework by using XML or annotations .

Not exactly. There are either only two ways to configure the Spring framework. The two basic configuration tools for the Spring framework are:

  • XML files (outside java files)
  • Java (5 +) based annotations (inside java files)

Both of them can be used to:

  • configure an application context (meaning adding beans) - the constructors of concrete application contexts accept xml files, packages to scan, or directly named classes to load
  • bootstrap an application context in the case of a web application - using web.xml vs using a class implementing WebApplicationInitializer

And last but not least:

  • you can scan annotations from an xml configuration file by using <context:component-scan/>
  • you can load a xml file from an annotated configuration bean by using @import

The second way called Java Based Configuration in your book, is a particular annotation @Configuration . A class annotated with it will normally be a bean in the application context, but it can also declare other beans with the @Bean annotation on one method. That's the reason why those classes are generally loaded directly instead of bean scanned.

The third way called Annotation Based Configuration , is simply a mixing of the two modes, where you use xml configuration at higher level and just scan packages for additional beans.


TL/DR: there are only 2 ways to configure an application context in the spring framework:

  • xml configuration files
  • java annotations

and they can be mixed

but every single bean can be declared in 3 ways:

  • from a xml file
  • with a @Bean annotation inside a @Configuration annotated bean
  • directly with a @Component (or any of the specialized annotations @Controller , @Service , etc.)

Now for your precise questions:

Why is the (so-called) Annotation Based Configuration actually using ClassPathXmlApplicationContext but not AnnotationConfigApplicationContext above?

Because the ApplicationContext is first initialized form a xml configuration file. Package scanning occurs later with the help of <context:scan ...> tags. You use an AnnotationConfigApplicationContext if you directly initialize it from configuration classes or through package scanning.

The Java Based Configuration explained in the book seems like what should be called Annotation Based Configuration.?

They call it Java Based because it needs no xml so configuration only uses Java

I have not taken a look at the book, but your assumptions are actually correct.

To start a Spring application and have all the beans instantiated by the framework using XML configured beans, you must use a ClassPathXmlApplicationContext.

There are 2 ways to configure beans in Spring:

1) XML beans 2) Annotation approach

Basically, XML beans were used in Spring 2.5-3 and Annotations approach is used more in Spring 4.

@Bean // is a way to create a bean. It is the equalivant of the beans tag in XML.

@Configuration // is a way to tell the Spring container that this class is a list of configuration beans

Spring has 2 spring containers:

1) BeanFactory 2) ApplicationContext

A BeanFactory is the most simplest container and only accepts one config file. An ApplicationContext is the most advanced Spring container and is used in enterprise applications as it accepts an array of config files, has JNDI integration, EJB integration and supports internationalisation of messages.

I hope that helps.

Let me first show different in coding first:

  1. XML: you have to register your spring bean inside xml context file using <bean/>
  2. Java Configuration: you have to use @Configuration and @Bean to register your spring bean in context.

  3. Annotation: by using @Component and its friends is actually common could be used with other 2 using:

    1. in xml using <context:component-scan/>
    2. in java config using @ComponentScan

Why used ClassPathXmlApplicationContext because he used xml to configure component scan but if he used @ComponentScan then will sure use AnnotationConfigApplicationContext

So for me I consider it as 2 ways to initialize spring context xml or java configuration and Annotation is option could be used by any one of them or not used at all.

The three ways to configure the spring framework are not at all meant to be mutually exclusive. Actually, my guess is that on average you will find at least two of them used together.

The annotation based configuration is the least likely to be used stand-alone, simply because it relies on metadata that is inherently scattered throughout the source code.

The AnnotationConfigApplicationContext can be used to fire up a pure annotation-based context , but you will need to pass in all your classes annotated as @Component or derivatives, rather than passing in a single (or a couple of) @Configuration -annotated class(es) -- which is usually not practical.

Although this is pretty much the same as statically listing the beans in XML or Java configuration, the fact that you'll need to do this in code when you build the application context itself makes it less useful, as you can't benefit of the various clever ways of automatically firing up an application context (in web contexts and so on).

That's why you will probably want to be able to have the full object graph metadata assembled in one go, and that can only be achieved with either XML or Java-based config , which rely on "centralized" metadata describing the whole object graph.

For both XML and Java-based approaches, this "centralized metadata" ( <beans> or @Configuration ) can be defined statically (with explicit <bean> or @Bean definitions) or dynamically (using <component-scan> or @ComponentScan ). So it's reasonable to say that these two approaches are just different formats with pretty much the same capabilities which can both benefit of annotation-based config for gathering the "de-centralized" metadata.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM