Injection of beans in the Spring core family

Hello, Hello, two blog posts to share the Spring container is created, and the Bean’s life cycle, this article explain the Bean injection for everyone today, is the Bean’s some injection pattern, configuration, and then tell me something about the author’s experience, this article also are basic things, good, old routines, Article structure:

  1. Xml-based configuration
  2. Annotation-based configuration
  3. Configuration based on Spring Config
  4. A mixture of several configuration methods

1. Xml-based configuration

This section alone, if said in detail, a blog is not enough, because the knowledge point is more, more miscellaneous, and, most of the life is not used. So I want to think, or directly flat directly on the key, a lot of unnecessary can mention it.

1.1 DTD format

Spring’s XML configuration file is in DTD format. Many people ignore the initial configuration of this XML, so I’ll mention it here:

Beans tag format:

  • The XMLNS attribute defines a namespace, which is the prefix with which all files define beans, like aop:config. The AOP of this tag is the AOP namespace, without the added namespace, which is the default namespace.

  • The XSI attribute specifies the format file XSD based on the fully qualified name.

  • Format for the XMLNS attribute: XMLNS: namespace =” fully qualified name of the namespace (optionally named 123)”

  • XSD format: “XMLNs-defined namespace “+” space “+” XSD file”

Here’s what specifying XSD does: when you type the first half of the <bea, it prompts you for all. This is actually what the IDE lists for you from the XSD file.

1.2 define the Bean

To define beans in an XML file, the simple one is:

<bean id="stu" class="com.zdy.Student" >
    <property name="name"><value>Zhang SAN</value></property>
</bean>
Copy the code

It’s injected according to the setter method. Don’t worry about injecting properties according to constructors. Xiba, the blogger has not operated like this in so many years. It’s all injected according to the setter. And then, XML has some special characters that need to be escaped. Let me give you a table:

As for the Internet said there is a :<! [CDATA[]]> < span style = “box-sizing: border-box; One is inconvenient, and the other is that p-namespaces are not supported. We’ll talk about the P namespace in a second.

The above example is the injected constant, and then the interdependencies between beans:

<bean id="car" calss="..." />
<bean id="boss" class="..." >
    <property name="car">
        <ref bean="car"></ref>
    </property>
</bean>
Copy the code

Some of the other collection injection, cascading injection, I’m not going to talk about it, it doesn’t work.

1.3 XML simplified configuration of the P namespace

As you can see, the configuration above is complex and requires the ref tag to be used when configuring dependencies between beans. Now let’s take a look at the simplified configuration and auto-injection. P namespaces that Spring2.5 introduced to simplify the configuration.

/ / before use<bean id="stu" class="com.zdy.Student" >
    <property name="name"><value>Zhang SAN</value></property>
</bean>/ / after use<bran id="stu" class="..." p:name="Zhang" />
Copy the code

Then say the format:

  • For literal constants: p: attribute name =”..”
  • For attributes of reference beans: p: attribute name -ref=”…”

Then auto-injection: you can see that if you use the REF tag to inject bean dependencies, the programmer will die. For example, a Controller layer Bean may depend on more than a dozen Service layer beans. Write is configured one by one. Certainly not. So auto injection comes out. @autowired annotation, we’ll talk about that later. Just to mention it.

Then, the tag is used to import multiple XML configuration files into a single XML configuration file.

2. Annotation-based configuration

As you can see above, to inject beans into the Spring container, you can use tags, then inject some properties and so on. And references between beans can use ref tags. In fact, this kind of operation in the work basically no company will adopt. Because it’s too much trouble, because when you match it to the REF tag, you’re really going to die. In our work, we will definitely use annotations to configure our beans.

  1. Add the scan path to the XML file or Java Config class.
<context:component-scan base-package="...">
Copy the code
  1. We wrote our own bean with @Component,@Controller,@Service, @DAO
@Component
public class UerDao {
    ...
}
Copy the code

Thus, our UserDao is injected into the Spring container. So how does this configuration address interdependencies? @AutoWired

@Controller public class UserController{ @Autoired private UserService userService; . }Copy the code

@autoired will automatically inject the Bean based on the type. How easy is that? I won’t expand on some of the other parameters.

3. Configuration based on Spring Config

Give a Config class directly:

@Configuration
public class UserJedisConfig {

    @Bean
    public CacheManager cacheManager(final RedisTemplate redisTemplate) {
        return new RedisCacheManager(redisTemplate);
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate2(final RedisConnectionFactory factory) {
        final RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new RedisObjectSerializer());
        template.afterPropertiesSet();
        returntemplate; }}Copy the code

@Configuration contains @Component. To be clear, when this Bean is added to the Spring container, all beans returned by the @Bean method annotated inside it are put into the Spring container. I won’t go into the specific syntax. There are three ways the @Configuration class can be added to the Spring container. One is in XML via

scan. One way is to use the @ComponentScan annotation from other Config classes, which does the same thing, scanning the POJOs in the configuration path. The last way is to specify the Config class directly when creating the container, instead of the XML configuration file, as discussed in the previous blog.

4. Multiple configuration modes can be used

Well, there are really three ways to add beans to the Spring container. And it’s all very basic. Let me give you a few practical lessons:

  1. Annotations are larger than XML configuration. You can also feel the convenience of annotations.
  2. Self-written beans are all injected into the container using annotations. It doesn’t matter whether the container starts with an XML file or a Config class. As long as you add automatic scanning.
  3. When integrating some three-party frameworks (such as Jedis) that need to put three-party beans into the Spring container, there is no way to use annotations, you can use XML file configuration or config class configuration.

Finally, a comparison diagram and usage scenario diagram are given:

Finally, I would like to say that the author has encountered some practical choices in these ways:

  1. I used to use “XML+ annotations “in a real estate company, which is more common and traditional. For Web projects, the container is started as an XML file, and then the scanned and scanned path is configured in the XML file. The self-made Bean is placed under the path and annotated like @Componenet. The dependencies depend on the @AutoWired annotation. If you reference some third-party frameworks and want to use beans that come with the framework, configure the tags to be added to the container in the XML. This is a more traditional use of the Spring container.
  2. If you have used Spring Boot, you should know that there is no XML file in Spring Boot. The container is enabled by a built-in Config class. This config class will automatically scan the following path. So any class we develop with @Component annotations will be added to the container. In general, Spring Boot has some auto injection mechanism that automatically creates beans based on configured parameters and automatically injects beans into the container. Developers can use it directly @autowired. In special cases, we will write a config class to inject a tripartite bean that Spring Boot does not have. Why do people who have used Spring Boot feel that Spring Boot is relatively simple? If you think about it, if you want to use Jedis, all you need is poM introduction. Then @AutoWired directly injects the appropriate bean, with no configuration at all. This is one of Spring Boot’s most central features. I will share with you how this automatic injection is implemented when I have the opportunity to talk about Spring Boot later.

conclusion

Ok, in fact, this section is relatively simple. As you can see, the author doesn’t explain how to use it in detail, such as some properties of @autowired and some syntax of @Configuration. The author just gives an example. As the author thinks that the focus of this article should be to grasp the mechanism of these kinds of injection beans, here are a few examples:

  1. Developers see the @Component annotation in their own projects. To know how the bean is being added (XML scan or config file scan),
  2. I received the project and found that the Web project did not have Spring’s XML master file. (It is important to consider whether the container is launched through the Config class.)
  3. The developer wants to add some tripartite beans to the container, using XML configuration or config class configuration. Well, this one to share with you, today is Monday, everyone work hard, make money to go home for the Spring Festival. Over,Hava a good day .