Bean annotation (Annotation) Configuration (1) - Load Bean via annotations


Spring series of tutorials


Bean can also be configured by way of Java annotations.

Java annotations directly added to the Bean Java classes require assembly.

Annotation is the class, method or on the special tag field declarations. For example, it is common @Overridethat a note, is to tell the compiler which is a method being overridden.

Annotations XML configuration configuration comparison

Notes configuration is more compact than XML configuration, especially when there are many Bean, can save a lot of things.

XML injection will be performed after injection of annotations, XML configuration it will cover annotation configuration.

1. Enable configuration notes

By default, Spring annotation configuration container is not enabled. Components need to open the scan function in Bean's XML configuration file, enable annotation configuration.


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
    <!-- 打开组件扫描,启用注解配置 -->
    <context:component-scan base-package="com.qikegu.demo"></context:component-scan>
    
    <!-- ... -->

</beans>

base-package="com.qikegu.demo"Specifies the path to scan the package.

2. Bean Java class to add @Componentannotations

Spring specify all classes in the package container scanning path, each time to find an @Componentannotation, it will register Bean, and set Bean ID.

The default Bean ID is the name of the class, but the first letter lowercase. If the class name to several consecutive start with a capital letter, the first letter is not lowercase. (Ie QIKEGUService -> QIKEGUService)


package com.qikegu.demo;

import org.springframework.stereotype.Component;
import org.springframework.context.annotation.Lazy;

@Component
@Lazy
public class App {
}

3. Obtain the bean container Spring

And XML configuration is similar to using the getBean()method returns Bean instance.

Example:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) {
    
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        
        // 获取Bean实例
        App app = context.getBean("app", App.class);
        // App app = (App) context.getBean("app");
    }
}

Guess you like

Origin www.cnblogs.com/jinbuqi/p/10977622.html