④【Spring】IOC - 基于注解方式 管理bean

简介: ④【Spring】IOC - 基于注解方式 管理bean



一、注解的功能


注解本身只是一种标记,是不能被执行的,但是框架功能检测到注解后,会根据当前位置注解标记的功能来执行具体的操作。

框架中的操作都由Java代码执行,注解只是告诉框架需要执行那些代码。





二、四个典型注解


  • @Component : 标记普通的组件
  • @Controller : 标记三层架构表述层中的控制器组件(controller)
  • @Service : 标记表述层中的业务逻辑组件(service)
  • @Repository : 标记持久化层组件(DAO)

@Controller、@Service、@Repository这三个注解只是在@Component注解的基础上起了三个新的名字,对于Spring使用IOC容器管理这些组件来说没有任何区别,也就是语法层面没有区别。之所以这么做是为了增加代码可读性,让我们能够便于分辨组件的作用。





三、扫描注解


①基本的扫描方式

  • XML配置文件中,配置自动扫描的包;
<context:component-scan base-package="com.haojin.ioc.component"/>
base-package属性 配置自动扫描的包
包名:使用注解组件类所在的包



②指定匹配模式

  • XML配置文件中,配置了自动扫描的包的基础上,指定匹配模式
<context:component-scan base-package="com.haojin.ioc.component"
                            resource-pattern="Test*.class"/>
resource-pattern属性 指定匹配模式
指定匹配模式外组件类的bean不会创建,所以获取没有创建的bean时会报错



③指定扫描时要排除的组件

  • XML配置文件中,指定不扫描的组件/扫描时排除的组件
<context:component-scan base-package="com.haojin.ioc.component">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
- context:exclude-filter标签,指定不扫描的组件
- type属性指定根据什么来进行排除,annotation取值表示根据注解来排除
- expression属性:指定排除规则的表达式,对于注解来说指定全类名即可



④指定仅扫描什么组件

  • 仅扫描 = 关闭默认规则 + 追加规则
  • 属性 use-default-filters ,取值false表示关闭默认扫描规则
  • context:include-filter标签:指定在原有扫描规则的基础上追加的规则(仅扫描)
  • expression属性:指定仅扫描规则的表达式,对于注解来说指定全类名即可
<context:component-scan base-package="com.haojin.ioc.component" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>



注:bean的id属性

在我们使用 XML 方式管理 bean 的时候,每个 bean 都有一个唯一标识——id 属性的值,便于在其他地方引用。现在使用注解后,每个组件仍然应该有一个唯一标识。


默认:类名首字母小写就是 bean 的 id。如:TestController 类对应 testController


指定:标记注解时,使用value属性指定

@Controller(value = "controller")
public class TestController {
}





四、自动装配


  • 前提:参与自动装配的组件,全部都必须在IOC容器中。(都需要创建bean)
  • 使用 @Autowired注解 实现自动装配


案例:

- TestController 需要 TestService;
- TestService 需要 TestDao;
- 同时在各个组件中声明要调用的方法。

- TestDao组件,含getMessage()方法

@Repository
public class TestDao {
    public void getMessage(){
        System.out.println("all girls are the same...");
    }
}


- TestService组件,@Autowired注解标记 TestDao

//这个组件就是我们在三层架构中使用的业务逻辑组件。
@Service
public class TestService {
  //在成员变量上直接标记@Autowired注解即可
    @Autowired
    TestDao testDao;
    public void getMessage(){
        testDao.getMessage();
    }
}


- TestController组件,@Autowired注解标记 TestService

//这个组件就是我们在三层架构中表述层里面,使用的控制器。以前是Servlet,以后我们将会使用Controller来代替Servlet。
@Controller(value = "controller")
public class TestController {
    @Autowired
    TestService testService;
    public void getMessage(){
        testService.getMessage();
    }
}



自动装配的流程

在@Autowired注解的下一行,
可以使用@Qualifier注解 指定 bean 的 id ,不使用则默认id;
@Autowired
    @Qualifier(value = "beanIdName")





五、完全注解开发


  • @Configuration注解 将一个普通的类标记为 Spring 的配置类;
  • @ComponentScan注解 配置类中配置自动扫描的包;
  • @Bean注解 相当于XML文件中的bean标签,标记的方法的返回值会被放入 IOC 容器,默认以方法名作为 bean 的 id;
  • 使用 AnnotationConfigApplicationContext 根据配置类创建 IOC 容器对象;


⚪配置类

//@Configuration注解 将一个普通的类标记为 Spring 的配置类
@Configuration
//@ComponentScan注解 配置类中配置自动扫描的包
@ComponentScan("com.haojin.ioc.component")
public class TestController {
    // @Bean 注解相当于 XML 配置文件中的 bean 标签
    // @Bean 注解标记的方法的返回值会被放入 IOC 容器
    // 默认以方法名作为 bean 的 id
    @Bean
    public void getMessage(){
    }
}



⚪测试

public class TestComponent {
    @Test
    public void test1(){
    //使用ClassPathXmlApplicationContext读取XML配置文件的方式
//        ApplicationContext context = new ClassPathXmlApplicationContext("component_bean.xml");
        //根据配置类创建 IOC 容器对象;
        ApplicationContext context = new AnnotationConfigApplicationContext(TestController.class);
        TestController controller = context.getBean(TestController.class);
        System.out.println(controller);
    }
}





六、整合Junit 4


优点:
1:不需要自己创建IOC容器对象了
2:任何需要的bean都可以在测试类中直接享受自动装配


⚪组件类

@Controller(value = "controller")
public class TestController {
}


⚪XML配置文件

component_bean.xml配置文件

<context:component-scan base-package="com.haojin.ioc.component" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
</beans>


⚪测试类

  • junit的@RunWith注解:指定Spring为Junit提供的运行器
  • Spring的@ContextConfiguration注解: 指定Spring配置文件的位置
**
 * @author .29.
 * @create 2023-01-21 14:18
 */
// junit的@RunWith注解:指定Spring为Junit提供的运行器
// Spring的@ContextConfiguration指定Spring配置文件的位置
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = {"classpath:component_bean.xml"})
public class TestComponent {
    //自定装配
    @Autowired
    TestController controller;
    @Test
    public void test1(){
        System.out.println(controller);
    }
}





七、整合Junit 5


⚪依赖

<!--junit5测试-->
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.9.0</version>
    </dependency>



⚪测试类 注解

//两种方式均可
//方式一
//@ExtendWith(SpringExtension.class)
//@ContextConfiguration("classpath:component_bean.xml")
//方式二
@SpringJUnitConfig(locations = "classpath:component_bean.xml")
其余与整合junit 4一致





🚀小结


  • @Component : 标记普通的组件
  • @Controller : 标记三层架构表述层中的控制器组件(controller)
  • @Service : 标记表述层中的业务逻辑组件(service)
  • @Repository : 标记持久化层组件(DAO)
  • @Autowired: 实现自动装配
  • @Qualifier: 用在@Autowired下一行,指定 bean 的 id
  • @Configuration : 将一个普通的类标记为 Spring 的配置类
  • @ComponentScan: 配置类中配置自动扫描的包
  • @Bean 相当于XML文件中的bean标签,标记的方法的返回值会被放入 IOC 容器,默认以方法名作为 bean 的 id
  • @RunWith:指定Spring为Junit提供的运行器
  • @ContextConfiguration: 指定Spring XML配置文件的位置




目录
相关文章
|
14天前
|
XML Java 测试技术
Spring IOC—基于注解配置和管理Bean 万字详解(通俗易懂)
Spring 第三节 IOC——基于注解配置和管理Bean 万字详解!
95 26
|
17天前
|
缓存 Java 数据库
SpringBoot缓存注解使用
Spring Boot 提供了一套方便的缓存注解,用于简化缓存管理。通过 `@Cacheable`、`@CachePut`、`@CacheEvict` 和 `@Caching` 等注解,开发者可以轻松地实现方法级别的缓存操作,从而提升应用的性能和响应速度。合理使用这些注解可以大大减少数据库的访问频率,优化系统性能。
162 89
|
2月前
|
Java Spring
【Spring】方法注解@Bean,配置类扫描路径
@Bean方法注解,如何在同一个类下面定义多个Bean对象,配置扫描路径
180 73
|
4天前
|
监控 Java Spring
SpringBoot:SpringBoot通过注解监测Controller接口
本文详细介绍了如何通过Spring Boot注解监测Controller接口,包括自定义注解、AOP切面的创建和使用以及具体的示例代码。通过这种方式,可以方便地在Controller方法执行前后添加日志记录、性能监控和异常处理逻辑,而无需修改方法本身的代码。这种方法不仅提高了代码的可维护性,还增强了系统的监控能力。希望本文能帮助您更好地理解和应用Spring Boot中的注解监测技术。
33 16
|
2月前
|
XML Java 数据格式
【SpringFramework】Spring IoC-基于XML的实现
本文主要讲解SpringFramework中IoC和DI相关概念,及基于XML的实现方式。
116 69
|
2月前
|
Java Spring 容器
【SpringFramework】Spring IoC-基于注解的实现
本文主要记录基于Spring注解实现IoC容器和DI相关知识。
60 21
|
27天前
|
XML Java 应用服务中间件
Spring Boot 两种部署到服务器的方式
本文介绍了Spring Boot项目的两种部署方式:jar包和war包。Jar包方式使用内置Tomcat,只需配置JDK 1.8及以上环境,通过`nohup java -jar`命令后台运行,并开放服务器端口即可访问。War包则需将项目打包后放入外部Tomcat的webapps目录,修改启动类继承`SpringBootServletInitializer`并调整pom.xml中的打包类型为war,最后启动Tomcat访问应用。两者各有优劣,jar包更简单便捷,而war包适合传统部署场景。需要注意的是,war包部署时,内置Tomcat的端口配置不会生效。
200 17
Spring Boot 两种部署到服务器的方式
|
27天前
|
Dart 前端开发 JavaScript
springboot自动配置原理
Spring Boot 自动配置原理:通过 `@EnableAutoConfiguration` 开启自动配置,扫描 `META-INF/spring.factories` 下的配置类,省去手动编写配置文件。使用 `@ConditionalXXX` 注解判断配置类是否生效,导入对应的 starter 后自动配置生效。通过 `@EnableConfigurationProperties` 加载配置属性,默认值与配置文件中的值结合使用。总结来说,Spring Boot 通过这些机制简化了开发配置流程,提升了开发效率。
59 17
springboot自动配置原理
|
1月前
|
XML JavaScript Java
SpringBoot集成Shiro权限+Jwt认证
本文主要描述如何快速基于SpringBoot 2.5.X版本集成Shiro+JWT框架,让大家快速实现无状态登陆和接口权限认证主体框架,具体业务细节未实现,大家按照实际项目补充。
80 11
|
1月前
|
缓存 安全 Java
Spring Boot 3 集成 Spring Security + JWT
本文详细介绍了如何使用Spring Boot 3和Spring Security集成JWT,实现前后端分离的安全认证概述了从入门到引入数据库,再到使用JWT的完整流程。列举了项目中用到的关键依赖,如MyBatis-Plus、Hutool等。简要提及了系统配置表、部门表、字典表等表结构。使用Hutool-jwt工具类进行JWT校验。配置忽略路径、禁用CSRF、添加JWT校验过滤器等。实现登录接口,返回token等信息。
343 12