zoukankan      html  css  js  c++  java
  • java spring boot @bean的用法

    java spring boot @bean的用法

    1 先看下spring bean xml中的应用

    package tutorialspoint;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    public class MainApp {
        public static void main(String[] args) {
            ApplicationContext context =
                    new ClassPathXmlApplicationContext("Beans.xml");
            HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
            obj.getMessage();
    
    
        }
    }
    package tutorialspoint;
    
    public class HelloWorld {
        private String message;
        public void setMessage(String message){
            this.message  = message;
        }
        public void getMessage(){
            System.out.println("Your Message : " + message);
        }
    }
    <?xml version="1.0" encoding="UTF-8"?>
    
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    
        <bean id="helloWorld" class="tutorialspoint.HelloWorld">
            <property name="message" value="Hello World111!"/>
        </bean>
    
    </beans>

    A类调用B类 就是 A通过bean.xml 获取B 。。。。。。 反正我不喜欢这种设计模式 感觉不太好用。。。

    2 再看看还有个写法

    不用bean.xml 用@Configuration @Bean  代码bean.xml

    package tutorialspoint;
    import org.springframework.context.annotation.*;
    @Configuration
    public class HelloWorldConfig {
        @Bean
        public HelloWorld helloWorld(){
            return new HelloWorld();
        }
    }
    package tutorialspoint;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    public class MainApp {
        public static void main(String[] args) {
            ApplicationContext ctx =
                    new AnnotationConfigApplicationContext(HelloWorldConfig.class);
            HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
            helloWorld.setMessage("Hello World!");
            helloWorld.getMessage();
    
    
        }
    }

    感觉还是看xml舒服。。

  • 相关阅读:
    flask 非要将视图和app放在一个空间
    spring mvc 实用的思想
    不能在windows上使用但值得关注的项目
    AI 医疗
    我也是混乱了同步盘和网盘
    常用free文献数据库
    机器学习中如何处理不平衡数据?
    自己制作的学习笔记视屏,还有记录的代码。
    函数的指针(一)写一个能对任意数组排序的冒泡排序
    自己写一个swap函数交换任意两个相同类型元素的值 对空指针的使用 字节大小的判断(二)了解原理
  • 原文地址:https://www.cnblogs.com/newmiracle/p/12760281.html
Copyright © 2011-2022 走看看