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

相关推荐
程序员小假6 分钟前
我们来说一说 Redisson 的原理
java·后端
chirrupy_hamal8 分钟前
网络编程 - TCP 篇
java
白衣鸽子10 分钟前
数据库高可用设计的灵魂抉择:CAP权衡
数据库·后端
xyy12320 分钟前
SixLabors.ImageSharp 使用指南
后端
notillusion30 分钟前
KWW#71843
java·php·程序优化
xiangzhihong838 分钟前
Spring Boot集成SSE实现AI对话的流式响应
人工智能·spring boot
Deschen1 小时前
设计模式-抽象工厂模式
java·设计模式·抽象工厂模式
齐木卡卡西在敲代码1 小时前
java流式编程学习
java
阑梦清川1 小时前
docker部署tomcat和nginx
后端
ʚ希希ɞ ྀ1 小时前
SpringBoot的学习
java·spring boot·学习