Spring注解开发--- 纳入IOC

I、springIOC容器的2种形式

1、xml配置文件:applicationContext.xml
  •   获取容器 :ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml");
    
2、注解:带有@Configuration注解的类(配置类)
  •   ApplicationContext context  = new AnnotationConfigApplicationContext(Config.class) ;
    
* 注意:两种形式获取的Ioc容器是 独立的

II、注解形式 给IOC容器中存放Bean:

1.必须有@Configuration注解(配置类)
2.形式:
①、三层组件加入IOC容器: 给个各类加 注解 、 扫描器识别注解所在包
  • 给三层组件 分别加注解(@Controller、@Service、@Repository -> @Component)
②、纳入ioc 配置 扫描器:
  • a、xml配置文件 : <context:component-scan base-package=“需要扫描的包名” ></context:component-scan>
  • b、注解形式 :@ComponentScan(value = “需要扫描的包名”)
逻辑:
  •   ①、 在三层类上加注解  ,让ioc识别,扫描器
    
  •   ②、注解扫描器
    
* 注意 : component-scan:只对三层组件负责

Student : 实体类

	import lombok.Getter;
	import lombok.Setter;
	@Setter
	@Getter
	public class Student {
	    private String name;
	    private int age;
	    
	    public Student() {
	        System.out.println("无参");
	    }
	    public Student(String name, int age) {
	        this.name = name;
	        this.age = age;
	        System.out.println("有参");
	    }
	}

Config.class :配置类

	@Configuration
	public class Config {
		public Student myStudent() {
			Student ls = new Student("ls", 23);
			return ls;
		}
	}

Test.class

	public static void testAnnotation(){
		//获取容器对象
		ApplicationContext context =  new AnnotationConfigApplicationContext(MyConfig.class);
		//获取容器中的bean
		Student student = (Student)context.getBean("student");
		//获取容器中所有的bean 的id
		String[] beanDefinitionNames = context.getBeanDefinitionNames();
		for(String name : beanDefinitionNames){
			System.out.println(name);
		}
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值