Fork me on GitHub

Spring-09-使用Java的方式配置Spring

9. 使用Java的方式配置Spring

我们现在要完全不使用Spring的xml配置,全权使用Java来配置Spring!

JavaConfig是Spring的一个子项目,在Spring4之后,他成为了一个核心功能。

在这里插入图片描述

实体类:

public class User {
    private String name;

    public String getName() {
        return name;
    }
    @Value("huba") //属性注入值
    public void setName(String name) {
        this.name = name;
    }
}

配置类:

package com.kuang.config;

import com.kuang.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration //这个也会spring容器托管,注册到容器中,因为他本来就是一个@Component
//@Configuration:代表这个一个配置类,就等同于beans.xml
@ComponentScan("com.kuang.pojo")
@Import(MyConfig2.class)
public class MyConfig {

    //注册一个bean,就相当于我们之前写的<bean>标签
    //方法名就相当于bean标签中的id
    //方法的返回值就相当于bean标签中的class属性
    @Bean
    public User user(){
        return new User();//就是返回要注入bean的对象
    }
}

测试类:

import com.kuang.config.MyConfig;
import com.kuang.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class myTest {
    @Test
    public void test(){
        //如果完全使用配置类方式,只能通过AnnotationConfigApplicationContext获取容器,通过配置类的class对象加载!
        ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        User user = context.getBean("user", User.class);
        System.out.println(user.getName());
    }
}

这种纯Java的配置方式,在SpringBoot中随处可见!

posted @ 2020-08-25 14:12  CodeHuba  阅读(139)  评论(0编辑  收藏  举报