2.3.3 spring属性注入-注解注入-全注解-配置类扫描

代码:

spring2-属性注入-全注解-配置类扫描.zip - 蓝奏云文件大小:12.3 K|https://www.lanzouw.com/iPK5vvq21uf

这个博客,我们使用全注解的方式来扫描java bean

1、创建Category和Product类

package com.how2j.pojo;
//使用注解配置, 不需要定义set函数,

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//定义java bean, id为c
@Component("c")
public class Category {
    @Value("4")
    private int id;
    @Value("Category 1")
    private String name;

    //如果使用注解定义java bean,必须有无参构造函数。下面存在有参构造方法,所以如果使用注解必须手动写无参构造函数
    public Category() {
    }


    public Category(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Category{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
package com.how2j.pojo;
//这个类使用注解配置
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

//因为这个类没在xml文件中定义,所以使用注解来将这个类设置成java bean, 并设置id
@Component("p")
public class Product {
    //普通属于类型
    @Value("2")
    private int id;
    @Value("product test")
    private String name;
    //引用类型属性注入
    //这里的c是java bean的id,即Category中定义的@ComPonet("c")
    @Resource(name="c")
    private com.how2j.pojo.Category category;

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

2、创建配置类用于扫描java bean,这里的配置类只用来扫描,不用来定义bean

package com.how2j.pojo;

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

@Configuration  //可以将这个理解成xml中的<beans>
//使用配置类扫描批量注册,只能注册加了(@Repository,@Service, @Controller, @Componet类)
@ComponentScan(basePackages = "com.how2j.pojo")

public class SpringConfig {
}

3、测试

package test;

import com.how2j.pojo.Category;
import com.how2j.pojo.Product;
import com.how2j.pojo.SpringConfig;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestSpring {

    @Test
    //spring的控制翻转
    public void test1(){
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        //这里的c是在定义Category类中
        Category c = (Category) context.getBean("c");

        System.out.println(c);
    }

    @Test
    //测试spring的属性注入
    public void test2(){
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        //这里的p是定义在类里的, 即@Component("p")
        Product p = (Product) context.getBean("p");

        System.out.println(p);
    }
}

补充:下面是目录结构

扫描二维码关注公众号,回复: 13596413 查看本文章

猜你喜欢

转载自blog.csdn.net/stay_zezo/article/details/120941073
今日推荐