# Spring教程 - 5 IoC容器 - 基于注解配置(2)

继续基于注解配置。


# 5.5 全注解开发

在上面基于注解的配置,一开始还是创建了一个 bean.xml ,然后开启了注解配置。

其实我们可以使用全注解开发,这个 XML 文件都可以去掉。

一般在项目中,我们会创建一个配置类,在这个配置类上通过相关的注解,来启用 Spring 注解配置,从而替换 XML,实现全注解开发。


举个栗子:

首先将 bean.xml 都删掉。

然后在指定的包下创建一个类,一般都叫 config 包,例如 com.foooor.hellospring.config.SpringConfig.java,名称自定义。

package com.foooor.hellospring.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration  // 配置类
@ComponentScan("com.foooor.hellospring")  // 开启组件扫描,并指定扫描的包
public class SpringConfig {
}
1
2
3
4
5
6
7
8
9
  • 在上面的配置类,使用 @Configuration 注解标识这是一个配置类。
  • 然后使用 @ComponentScan 注解开启组件扫,并指定扫描的包。

接下来就可以测试了:

package com.foooor.hellospring;

import com.foooor.hellospring.config.SpringConfig;
import com.foooor.hellospring.controller.UserController;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * 测试类
 */
public class UserTest {

    @Test
    public void testUserService() {
        // 加载配置类
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        UserController userController = context.getBean(UserController.class);
        userController.getUser();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  • 在测试类中,要使用 AnnotationConfigApplicationContext 加载配置类,然后就可以获取 bean 了。

当然,还是那句话,这里只是测试,在实际的开发中,这些代码都是不需要的。


内容未完......