• Spring59


    9、使用Java的方式配置Spring


    文件目录结构:

    配置类MyConfig:

    package com.kuang.config;
    
    import com.kuang.pojo.User;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Import;
    
    // @Configuration代表这个是一个配置类,就和我们之前看的beans.xml
    @Configuration
    @ComponentScan("com.kuang.pojo")
    @Import(MyConfig2.class)
    public class MyConfig {
    
        //注册一个bean,就相当于之前写过的bean标签
        //这个方法的名字,就相当于bean标签中的id属性
        //这个方法的返回值,就相当于bean标签中的class属性
        @Bean
        public User getUser(){
            return new User(); //就是返回要注入到bean的对象!
        }
    }
    

    MyConfig2类:

    package com.kuang.config;
    
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class MyConfig2 {
    }
    

    User类:

    package com.kuang.pojo;
    
    import org.springframework.beans.factory.annotation.Value;
    
    public class User {
        private String name;
    
        public String getName() {
            return name;
        }
    
        @Value("Tom")
        public void setName(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }
    

    MyTest类:

    import com.kuang.config.MyConfig;
    import com.kuang.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(MyConfig.class);
            User getUser = (User) context.getBean("getUser");
            System.out.println(getUser.getName());
    
        }
    }
    

    这种纯Java的配置方式,在SpringBoot中随处可见!

  • 相关阅读:
    期末考试(优先队列)
    看病要排队《优先队列》
    Windows Message Queue(优先队列)
    Stones(优先队列)
    懒省事的小明(优先队列)
    产生冠军(set,map,拓扑结构三种方法)
    Web轻量级扫描工具Skipfish
    Web侦察工具HTTrack (爬取整站)
    文件上传漏洞绕过技巧
    Python爬虫之selenium的使用(八)
  • 原文地址:https://www.cnblogs.com/techgy/p/16088142.html
Copyright © 2020-2023  润新知