第四节:如何使用注解方式从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企业级应用开发》

相关推荐
xieliyu.3 小时前
Java算法精讲:双指针(三)
java·开发语言·算法
星辰徐哥3 小时前
Spring Boot 微服务架构设计与实现
spring boot·后端·微服务
星辰徐哥3 小时前
Spring Boot 数据导入导出与报表生成
spring boot·后端·ui
明夜之约3 小时前
Spring Boot 自动装配源码
java·spring boot·后端
Leaton Lee3 小时前
Spring Boot分层架构详解:从Controller到Service再到Mapper的完整流程
java·spring boot·后端·架构
Micro麦可乐3 小时前
Spring Boot 实战:从零设计一个短链系统(含完整代码与数据库设计)
数据库·spring boot·后端·哈希算法·雪花算法·短链系统
Jinkxs3 小时前
Resilience4j- 与 Spring Boot 快速集成:自动配置与基础注解使用
java·spring boot·后端
毕设源码_郑学姐3 小时前
计算机毕业设计springboot网络相册设计与实现 基于Spring Boot框架的在线相册管理系统开发与应用 Spring Boot驱动的网络影集设计与实践
spring boot·后端·课程设计
辣机小司3 小时前
【踩坑记录:Spring Boot 配置文件读取值不一致?警惕 YAML 的“八进制陷阱”与 SnakeYAML 版本之谜】
java·spring boot·后端·yaml·踩坑记录
一条小锦吕*3 小时前
基于Spring Boot + 数据可视化 + 协同过滤算法的推荐系统设计与实现(源码+论文+部署全讲解)
spring boot·算法·信息可视化