初学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());

    }
}
相关推荐
zcmodeltech20 分钟前
反应装置模型控制系统设计与实现:多设备协同联动方案
java·网络·数据库·stm32·嵌入式硬件·能源·制造
码视野32 分钟前
基于 Spring Boot + Vue3 的【城市地下燃气管网微泄漏感知与相邻地下空间燃爆预警中台】设计与实现(含PRD/三端高保真源码/大屏)
java·前端·人工智能·spring boot·后端
2601_962071571 小时前
数据库系统架构与DBMS功能探微:现代信息时代数据管理的关键
java·开发语言·数据库
梦想的旅途21 小时前
如何高效调用企业微信通讯录API管理组织架构
java·开发语言·企业微信
2601_962065251 小时前
2.启动mysql容器
java·数据库·mysql
2601_962065491 小时前
PHP For 循环
android·java·php
2601_962201722 小时前
Java进阶,集合,Colllection,常见数据结构
java·数据结构·windows
彷徨而立2 小时前
【C/C++】多线程读写普通 int 变量的一些问题
java·c语言·c++
卓怡学长2 小时前
w175基于springboot校园二手物品交易平台
java·spring boot·spring·maven·intellij-idea
chen<>2 小时前
malloc 和 free 背后发生了什么?
java·linux·服务器·操作系统