Spring JavaConfig配置

9. JavaConfig 配置

我们现在要完全不使用Spring的xml配置了,全权交给lava来做

JavaConfig 是 Spring 的一个子项目,在 Spring 4 之后,它成为了一个核心功能!

User.java 实体类

package com.peng.pojo;

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

//这里这个注解的意思,就是说明这个类被Spring注册到了齐器中
@Component
public class User {
    private String name;

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}

MyConfig.java 配置类

package com.peng.config;

import com.peng.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;

//这个也会Spring容器托管,注册到容器中。因为他本来就是一个@Component
@Configuration //@Configuration代表这是一个配置类,跟beans.xml一样
@ComponentScan("com.peng")
@Import(MyConfig2.class) //合并其他beans配置
public class MyConfig {

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

MyTest.java 测试类

import com.peng.config.MyConfig;
import com.peng.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        //如果完全使用了配置类方式去做,我们就只能通过AnnotationConfig上下文来获取容器,通过配置类的class对象加载!
        ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        User user = context.getBean("user",User.class);
        System.out.println(user.getName());
    }
}

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

posted @ 2020-07-10 16:37  鹏懿如斯  阅读(655)  评论(0编辑  收藏  举报