Table of Contents
Written in front:
Case: @Component and @Scope usage analysis:
Case: @Autowired usage analysis one:
Case: @Autowired usage analysis two:
案例:@ImportResource和@Value用法分析:
案例:@Bean和@Scope用法分析:
Home Java javaTutorial Detailed explanation of usage code examples of Spring framework annotations

Detailed explanation of usage code examples of Spring framework annotations

Mar 18, 2017 am 10:36 AM

Written in front:

As we all know, among the JavaEE development frameworks , the Spring framework is the most used, and the positioning of annotations in the framework has become more and more obvious. Let’s make a joke: If it can be solved with one annotation, it will never be solved with a bunch of configuration and code; if it cannot be solved, then come with two annotations; (Hold on, don’t spray...)

1.@Component is a general annotation defined by Spring and can annotate any bean.

2.@Scope defines the scope of the bean. Its default scope is "singleton". In addition, there are prototype, request, session and global session.

Case: @Component and @Scope usage analysis:

BeanAnnotation class:

@Scope
@Component
public class BeanAnnotation {

    public void say(String arg) {
        System.out.println("BeanAnnotation : " + arg);
    }

    public void myHashCode() {
        System.out.println("BeanAnnotation : " + this.hashCode());
    }

}
Copy after login

junit4 test class→TestBeanAnnotation class:

@RunWith(BlockJUnit4ClassRunner.class)
public class TestBeanAnnotation extends UnitTestBase {

    public TestBeanAnnotation() {
        super("classpath*:spring-beanannotation.xml");
    }

    @Test
    public void testSay() {
        BeanAnnotation bean = super.getBean("beanAnnotation");
        bean.say("This is test.");
    }

    @Test
    public void testScpoe() {
        BeanAnnotation bean = super.getBean("beanAnnotation");
        bean.myHashCode();
        bean = super.getBean("beanAnnotation");
        bean.myHashCode();
    }

}
Copy after login

SpringConfiguration file→spring-beanannotation.xml:

<context:component-scan base-package="com.beanannotation"></context:component-scan>
Copy after login
Copy after login

Let’s analyze the Spring configuration file first, base- package="com.beanannotation" indicates that we only process the annotations under this package name.

Then analyze the BeanAnnotation class and there is a say method. Assuming that we don't know what type of class this is (note: Service or DAO), we can use a general annotation @Component.

Finally analyze the TestBeanAnnotation class. In the testSay method, super.getBean("beanAnnotation") retrieves the bean from the IOC container and calls the bean's say method.

It’s time to ask the question. When we super.getBean, we get it from the IOC container through the bean’s id. So what is this id? Because when we add @Component to the BeanAnnotation class, the default id is beanAnnotation. If the name of @Component is specified, for example, when it is specified as @Component("bean"), the id obtained by super.getBean must be compared with it during unit test The test can be successful only if it corresponds.

Here I separate the @Scope annotation for analysis. There is a testScpoe method in the TestBeanAnnotation class. There is a myHashCode method in the BeanAnnotation class. You may be confused, why use this.hashCode()? Because @Scope specifies the scope of the bean, in order to ensure that the results of the test class are accurate and clear, the hash code value is used to determine whether it is the same object.

3.@Repository, @Service, and @Controller are more targeted annotations.

PS: Here we need to understand that these three annotations are based on the annotations defined by @Component:

①, @Repository is usually used to annotate DAO classes , which is what we often call the persistence layer.
②. @Service is usually used to annotate the Service class, which is the service layer.
③, @Controller is usually used in the Controller class, which is the control layer (MVC).

4.@Autowired is understood as the "traditional" setter method, which can be used in setter methods, constructors or member variables, and can perform automatic assembly of Spring Beans.

Case: @Autowired usage analysis one:

Spring configuration file → spring-beanannotation.xml:

<context:component-scan base-package="com.beanannotation"></context:component-scan>
Copy after login
Copy after login

SimpleMovie Lister class:

public class SimpleMovieLister {

    private MovieFinder movieFinder;

    @Autowired(required=false)
    public void setMovieFinder(MovieFinder movieFinder) {
        this.movieFinder = movieFinder;
    }

}
Copy after login

By default, if a suitable bean cannot be found, autowiring will failThrow an exception, we can @Autowired Annotate this set method and mark required=false to avoid it. However, this is not necessary. If the instance of movieFinder cannot be found, no exception will be thrown. Only when using it, it is found that movieFinder is null. In this case, we are required to When using it, first determine whether movieFinder is null. If so, a null pointer exception will be reported.

It is worth noting that we know that each class can have many constructors, but when using @Autowired, there is and can only be one constructor that can be marked as required=true (Note: required The default value is false).

Case: @Autowired usage analysis two:

BeanImplOne class:

@Order
@Component
public class BeanImplOne implements BeanInterface {

}
Copy after login

BeanImplTwo class:

@Order
@Component
public class BeanImplTwo implements BeanInterface {

}
Copy after login

BeanInterface class:

public interface BeanInterface {

}
Copy after login

BeanInvoker class:

@Component
public class BeanInvoker {

    @Autowired
    private List<BeanInterface> list;

    @Autowired
    private Map<String, BeanInterface> map;

    public void say() {
        if (null != list && 0 != list.size()) {
            for (BeanInterface bean : list) {
                System.out.println(bean.getClass().getName());
            }
        } else {
            System.out.println(" list is null !");
        }

        if (null != map && 0 != map.size()) {
            for (Map.Entry<String, BeanInterface> entry : map.entrySet()) {
                System.out.println(entry.getKey() + "      " + entry.getValue().getClass().getName());
            }
        } else {
            System.out.println("map is null !");
        }
    }
}
Copy after login

Test class TestInjection:

@RunWith(BlockJUnit4ClassRunner.class)
public class TestInjection extends UnitTestBase {

    public TestInjection() {
        super("classpath:spring-beanannotation.xml");
    }

    @Test
    public void testMultiBean() {
        BeanInvoker invoker = super.getBean("beanInvoker");
        invoker.say();
    }

}
Copy after login

首先,我们清楚BeanImplOne类和BeanImplTwo类是实现了BeanInterface接口的,在BeanInvoker类里面我们定义了list和map,我们通过@Autowired注解把BeanImplOne类和BeanImplTwo类注解进入其中。那么怎么证实是@Autowired注解把这两个类注入到list或者map中的呢?那么请看if循环语句和foreach循环打印,通过这个逻辑判断,如果能够打印出BeanImplOne类和BeanImplTwo类的路径名,就说明这样是可以的。如果有些小伙伴可能不信,那么可以试着不使用@Autowired注解,看结果怎么样。

测试类没有什么好说的,各位小伙伴有没有注意到@Order注解呢?这里需要解释的就是,如果在@Order注解里面输入执行的数字,比如1或者2,那么打印出来的路径名就会按顺序,也就是说通过指定@Order注解的内容可以实现优先级的功能。

5.@ImportResource注解引入一个资源,对应一个xml文件

6.@Value注解从资源文件中,取出它的key并赋值给当前类的成员变量

案例:@ImportResource和@Value用法分析:

MyDriverManager类:

public class MyDriverManager {

    public MyDriverManager(String url, String userName, String password) {
        System.out.println("url : " + url);
        System.out.println("userName: " + userName);
        System.out.println("password: " + password);
    }

}
Copy after login

config.xml:

<context:property-placeholder location="classpath:/config.properties"/>
Copy after login

StoreConfig类:

@Configuration
@ImportResource("classpath:config.xml")
public class StoreConfig {

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    @Bean
    public MyDriverManager myDriverManager() {
        return new MyDriverManager(url, username, password);
    }
Copy after login

这个案例我们使用注解配置jdbc数据库的连接,首先创建一个内含构造器的MyDriverManager类,然后配置config.xml里面的资源文件路径,以便@ImportResource注解获取,最后配置StoreConfig类。(注意url、username、password也必须要和数据库的保持一致哦)

详解StoreConfig类:首先我们定义三个成员变量,然后给每一个成员变量打上一个@value注解,注意@value里面的内容一定是资源文件里面的key值。这里的@ImportResource注解就是指明一个资源文件,在这个资源文件里面获取到对应的数据。那么@Configuration注解是用来干嘛的呢?为什么不用@Component注解呢?其实是这样的,@Component注解用于将所标注的类加载到 Spring 环境中,这时候是需要配置component-scan才能使用的,而@Configuration注解是Spring 3.X后提供的注解,它用于取代XML来配置 Spring。

7.@Bean注解用来标识配置和初始化一个由SpringIOC容器管理的新对象的方法,类似XML中配置文件的

ps:默认的@Bean注解是单例的,那么有什么方式可以指定它的范围呢?所以这里才出现了@Scope注解

8.@Scope注解,在@Scope注解里面value的范围和Bean的作用域是通用的,proxyMode的属性是采用哪一种的单例方式(一种是基于接口的注解,一种是基于类的代理)

案例:@Bean和@Scope用法分析:

    @Bean
    @Scope(value ="session",proxyMode = "scopedProxyMode.TARGET_CLASS")
    public UserPreferences userPreferences(){
        return new userPreferences();
    }

    @Bean
    public service userService(){
        UserService service =new SimpleUserService();
        service.setUserPreferences(userPreferences);
        return service;
    }
Copy after login

The above is the detailed content of Detailed explanation of usage code examples of Spring framework annotations. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

A new programming paradigm, when Spring Boot meets OpenAI A new programming paradigm, when Spring Boot meets OpenAI Feb 01, 2024 pm 09:18 PM

In 2023, AI technology has become a hot topic and has a huge impact on various industries, especially in the programming field. People are increasingly aware of the importance of AI technology, and the Spring community is no exception. With the continuous advancement of GenAI (General Artificial Intelligence) technology, it has become crucial and urgent to simplify the creation of applications with AI functions. Against this background, "SpringAI" emerged, aiming to simplify the process of developing AI functional applications, making it simple and intuitive and avoiding unnecessary complexity. Through "SpringAI", developers can more easily build applications with AI functions, making them easier to use and operate.

Use Spring Boot and Spring AI to build generative artificial intelligence applications Use Spring Boot and Spring AI to build generative artificial intelligence applications Apr 28, 2024 am 11:46 AM

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

What are the implementation methods of spring programmatic transactions? What are the implementation methods of spring programmatic transactions? Jan 08, 2024 am 10:23 AM

How to implement spring programmatic transactions: 1. Use TransactionTemplate; 2. Use TransactionCallback and TransactionCallbackWithoutResult; 3. Use Transactional annotations; 4. Use TransactionTemplate in combination with @Transactional; 5. Customize the transaction manager.

How are annotations used for test methods in the JUnit framework? How are annotations used for test methods in the JUnit framework? May 06, 2024 pm 05:33 PM

Annotations in the JUnit framework are used to declare and configure test methods. The main annotations include: @Test (declaration of test methods), @Before (method run before the test method is executed), @After (method run after the test method is executed), @ BeforeClass (method that runs before all test methods are executed), @AfterClass (method that runs after all test methods are executed), these annotations help organize and simplify the test code, and improve the reliability of the test code by providing clear intentions and configurations. Readability and maintainability.

The King of PHP Code Documentation: An Advanced Guide to PHPDoc The King of PHP Code Documentation: An Advanced Guide to PHPDoc Mar 02, 2024 am 08:43 AM

Introduction: PHPDoc is a comment standard for PHP code that produces easy-to-understand and informative documentation. By using specific comment tags, PHPDoc allows developers to provide important details about functions, classes, methods, and other code elements. This advanced guide takes an in-depth look at PHPDoc, demonstrating its capabilities and providing effective documentation strategies. Syntax and tags: PHPDoc comments start with double slashes (//) or multi-line comments (/**/). Here are some common annotation tags: @param: Defines the parameters of a function or method. @return: Specifies the return value of the function or method. @throws: Describes exceptions that may be thrown by a function or method. @var: defines the attributes or instances of the class

How to set transaction isolation level in Spring How to set transaction isolation level in Spring Jan 26, 2024 pm 05:38 PM

How to set the transaction isolation level in Spring: 1. Use the @Transactional annotation; 2. Set it in the Spring configuration file; 3. Use PlatformTransactionManager; 4. Set it in the Java configuration class. Detailed introduction: 1. Use the @Transactional annotation, add the @Transactional annotation to the class or method that requires transaction management, and set the isolation level in the attribute; 2. In the Spring configuration file, etc.

How do annotations in the Jackson library control JSON serialization and deserialization? How do annotations in the Jackson library control JSON serialization and deserialization? May 06, 2024 pm 10:09 PM

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

Detailed explanation of the operation steps of MyBatis annotations and dynamic SQL Detailed explanation of the operation steps of MyBatis annotations and dynamic SQL Feb 18, 2024 pm 03:29 PM

Detailed introduction to the usage of MyBatis annotation dynamic SQL MyBatis is a persistence layer framework that provides us with convenient persistence operations. In actual development, it is usually necessary to dynamically generate SQL statements based on business needs to achieve flexible data operations. MyBatis annotation dynamic SQL is designed to meet this demand.

See all articles