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

相关推荐
2501_916766541 分钟前
【Spring框架】SpringJDBC
java·后端·spring
谷哥的小弟7 分钟前
Spring Framework源码解析——ApplicationContextInitializer
java·spring·源码
布谷歌10 分钟前
在java中实现c#的int.TryParse方法
java·开发语言·python·c#
+VX:Fegn089513 分钟前
计算机毕业设计|基于springboot + vue图书管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
AntBlack14 分钟前
忍不住推荐 : AI 时代 ,桌面端真的可以考虑一下Go+Wails 的组合
后端·go·ai编程
码事漫谈20 分钟前
C++20协程如何撕开异步编程的牢笼
后端
while(1){yan}21 分钟前
网络基础知识
java·网络·青少年编程·面试·电脑常识
Ulana25 分钟前
计算机基础10大高频考题解析
java·人工智能·算法
黄俊懿32 分钟前
【深入理解SpringCloud微服务】Seata(AT模式)源码解析——@GlobalTransactional注解与@globalLock生效的原理
java·spring cloud·微服务·云原生·架构·系统架构·架构师
wheelmouse778837 分钟前
一个优雅、通用、零侵入的 CSV 导出工具类(Java 实战)
java·开发语言