第四节:如何使用注解方式从IOC中获取bean(自学Spring boot 3.x的第一天)

大家好,我是网创有方,上一节学习了如何理解Spring的两个特性IOC和AOP,这一节来基于上节的内容进行一个简单实践。这节要实现的效果是通过IOC容器获取到Bean,并且将Bean的属性显示打印出来。

第一步:创建pojo实体类student

新建一个pojo包,创建一个student实体类,通过右键Generate生成属性的getter和setter方法。

Student.java

复制代码
package cn.wcyf.wcai.pojo;

public class Student {

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    String  name;//姓名
    int age;//年龄
}

第二步:创建Appconfig容器配置类

新建一个config包,创建一个AppConfig.java类

新增代码如下:

复制代码
package cn.wcyf.wcai.config;

import cn.wcyf.wcai.pojo.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
    @Bean(name = "student")
    Student initStudent(){
        Student student = new Student();
        student.setAge(18);
        student.setName("小明");
        return student;
    }
}

上面注意注解@Configuration表示这个是一个java配置类,后面会根据这个配置生成一个IOC容器。@Bean(name = "student") 前面的@Bean声明这个方法将会把bean装填到IOC容器中。

如果@Bean后面跟着name="student"意味着后面的生成的Student类对象是student,如果不声明的话,后面调用Student的类对象要使用initStudent。所以为了更方便,建议大家增加name。

第三步:创建IOC容器,加载bean到容器中

代码如下:

复制代码
@SpringBootApplication

public class WcaiApplication {


    public static void main(String[] args) {
        var ctx = new AnnotationConfigApplicationContext(AppConfig.class);//创建一个IOC容器
        var student = ctx.getBean(Student.class);//从容器中获取一个Student bean
        System.out.println(student.getName());
        System.out.println(student.getAge());
    }
    @Controller
    public static class HelloController {
        @GetMapping("/test")
        public String test(HttpServletRequest request) {

            return "index";
        }
    }


}

注意,这里使用了new AnnotationConfigApplicationContext(Appconfig.class)替代了默认的 SpringApplication.run(WcaiApplication.class, args);

第四步:运行看效果

参考:《深入浅出Spring-Boot-3.x》

《SpringBoot企业级应用开发》

相关推荐
葫芦和十三5 小时前
图解 MongoDB 19|Oplog:复制的真正载体,不是文档是操作
后端·mongodb·agent
葫芦和十三5 小时前
图解 MongoDB 20|复制延迟与 catch up:Secondary 为什么跟不上
后端·mongodb·agent
IT_陈寒9 小时前
SpringBoot自动配置的坑,我的API突然就404了
前端·人工智能·后端
ServBay10 小时前
为什么说 MCP 是 2026 年开发者必须掌握的黄金协议?
后端·mcp
程序员夏洛10 小时前
Spring Boot 多模块项目中 IDEA 提示 Cannot resolve symbol 的一次排查记录
后端
子兮曰10 小时前
OpenMontage 深度解剖:你的 AI 编程助手,其实是个视频工作室
前端·后端·ai编程
子兮曰10 小时前
前端工具链的「Rust 化」:一场没有赢家的军备竞赛?
前端·后端·rust
爱勇宝12 小时前
从 Ctrl+CV 到 Enter:程序员正在失去什么
前端·后端·程序员
码事漫谈12 小时前
EdgeOne Makers + WorkBuddy:零基础也能快速搭建可上线的 AI 智能体(附图文教程)
后端