使用注解装配Bean

 注解@Component代表Spring Ioc 会把 这个类扫描生产Bean 实例,而其中 value属性代表这个类在Spring 中的id,这就相当于XML方式定义的Bean  的 id

现在有了这个类还不能测试,因为Spring IOC 并不知道  需要去哪里扫描对象,这时候可以使用一个Java Config 来告诉它

package com.nf147.manage.spring;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component(value = "role")
public class Big {

    @Value("1")
    private int id;

    @Value("可爱的小猪")
    private String name;

    @Value("1")
    private int age;


    @Override
    public String toString() {
        return "Big{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

注意:包名要和代码Big类一致,

@ComponentScan 代表 进行扫描,默认是扫描当前包的路径,spring 的包名要和它保持一致才能说扫描,否则是没有的

package com.nf147.manage.spring;

import org.springframework.context.annotation.ComponentScan;

@ComponentScan
public class PojoConfig {
}

调用代码:

使用了 AnnotationConfigApplicationContext类去初始化Spring Ioc 容器,它是配置项是Big的PojoConfig类,这样Spring Ioc 就会根据注解的配置去解析对应的资源,来生成容器。

package com.nf147.manage.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String[] args) {


        ApplicationContext context= new AnnotationConfigApplicationContext(PojoConfig.class);
        Big bean = context.getBean(Big.class);
        System.out.println(bean);


    }
}

 效果图:

 

猜你喜欢

转载自www.cnblogs.com/nongzihong/p/10122186.html