8_Spring_注解方式管理bean

01way / 2023-07-30 / 原文

8_Spring_注解方式管理bean

1注解方式创建对象IOC

导入依赖 aop

@Component    放在类上,用于标记,告诉spring当前类需要由容器实例化bean并放入容器中

该注解有三个子注解

@Controller   用于实例化controller层bean

@Service        用于实例化service层bean

@Repository  用于实例化持久层bean

当不确定是哪一层,就用Component

这几个注解互相混用其实也可以,但是不推荐

第一步:在applicationContext.xml中配置开启注解扫描

  1. <beans xmlns="http://www.springframework.org/schema/beans"
  2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    
  3.     xmlns:p="http://www.springframework.org/schema/p"
    
  4.     xmlns:c="http://www.springframework.org/schema/c"
    
  5.     xmlns:context="http://www.springframework.org/schema/context"
    
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans
    
  7.     http://www.springframework.org/schema/beans/spring-beans.xsd
    
  8.     http://www.springframework.org/schema/context
    
  9.    http://www.springframework.org/schema/context/spring-context.xsd
    
  10. ">
  11. <!--添加注解扫描,扫描指定的包,将包中的所有有注解的类实例化
    
  12. base-package 后面放要扫描的包
    
  13. 如果有多个包需要扫描,可以使用逗号隔开  com.msb.bean,com.msb.service
    
  14. 或者可以写上一层包路径  com.msb
    
  15. 可以通过注解指定bean的id@Component("user1")
    
  16. 如果不指定,则id默认是 类名首字母小写
    
  17. -->
    
  18. <context:component-scan
    
    base-package="com.msb.bean"></context:component-scan>

第二步:在类上添加注解,让spring容器给我们创建bean实例并存储于容器中

  1. package com.msb.bean;
  2. import org.springframework.stereotype.Component;
  3. /**
    • @Author: Ma HaiYang
    • @Description: MircoMessage:Mark_7001
  4. */
  5. @Component(value = "user1")
  6. public class User {
  7. }

测试代码

  1. package com.msb.test;
  2. import com.msb.bean.User;
  3. import org.junit.Test;
  4. import org.springframework.context.ApplicationContext;
  5. import org.springframework.context.support.ClassPathXmlApplicationContext;
  6. /**
    • @Author: Ma HaiYang
    • @Description: MircoMessage:Mark_7001
  7. */
  8. public class Test1 {
  9. @Test
    
  10. public void testGetBean(){
    
  11.     ApplicationContext context =new
    
    ClassPathXmlApplicationContext("applicationContext.xml");
  12.     User user = context.getBean("user1", User.class);
    
  13.     System.out.println(user);
    
  14. }
    
  15. }

组件扫描配置注解识别