初学Spring之 JavaConfig 实现配置

使用 Java 方式配置 Spring

写个实体类:

@Component 表示这个类被 Spring 接管了,注册到了容器中

java 复制代码
package com.demo.pojo;

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

@Component //这个类被Spring接管了,注册到了容器中
public class User {
    private String name;

    public String getName() {
        return name;
    }

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

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

写个配置类:

@Configuration 会被 Spring 容器托管,注册到容器中,因为他本来就是一个 @Component

@Configuration 代表这是一个**配置类,**和 beans.xml 一样

再写个方法:

@Bean:

注册一个 bean,相当于 bean 标签

这个方法的名字, 相当于 bean 标签中的 id 属性

这个方法的返回值, 相当于 bean 标签中的class 属性

java 复制代码
package com.demo.config;

import com.demo.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

//@Configuration会被Spring容器托管,注册到容器中,因为他本来就是一个@Component
//@Configuration代表这是一个配置类,和beans.xml一样
@Configuration
public class Config {

    /*
    注册一个bean,相当于bean标签
    这个方法的名字,相当于bean标签中的id属性
    这个方法的返回值,相当于bean标签中的class属性
     */
    @Bean
    public User getUser(){
        return new User(); //return返回要注入到bean的对象
    }
}

扫描:@ComponentScans("xx")

导入其他类:@Import(xx.class)

写个测试类:

如果完全使用了配置类方式去做,

只能通过 AnnotationConfig上下文来获取容器,

通过配置类的 class 对象加载

java 复制代码
import com.demo.config.Config;
import com.demo.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(Config.class);
        User getUser = (User) context.getBean("getUser");
        System.out.println(getUser.getName());

    }
}
相关推荐
输出输入1 天前
JAVA中return和break区别
java
董世昌411 天前
null和undefined的区别是什么?
java·前端·javascript
浅水壁虎1 天前
任务调度——XXLJOB3(执行器)
java·服务器·前端·spring boot
CC.GG1 天前
【C++】异常
java·jvm·c++
荒诞硬汉1 天前
抽象相关学习
java·学习
凸头1 天前
一个小问题:Swagger 不显示 VO,Swagger 泛型丢失
java
Pluchon1 天前
硅基计划4.0 算法 动态规划高阶
java·数据结构·算法·leetcode·深度优先·动态规划
编程彩机1 天前
互联网大厂Java面试:从Spring Boot到分布式缓存的技术场景解析
java·redis·分布式·缓存·大厂面试·技术解析·sprint boot
007php0071 天前
mac笔记本中在PHP中调用Java JAR包的指南
java·ide·python·面试·职场和发展·pycharm·php
sheji34161 天前
【开题答辩全过程】以 母婴店购物系统为例,包含答辩的问题和答案
java