zoukankan      html  css  js  c++  java
  • 【Spring-IOC】Bean定义与获取

    说明:所有bean均注册在pojo目录下

    方式1(不推荐):普通类 + bean.xml + ClassPathXmlApplicationContext

    <bean id="book" class="com.example.ioc.pojo.Book">
        <property name="name" value="${user}"/>
    </bean>

      然后通过ClassPathXmlApplicationContext 加载bean的XML文件,通过getBean获取Bean对象

    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
    Book book = applicationContext.getBean("book", Book.class);

     

    方法2:pojo对象增加@Component注解  + bean.xml(component-scan+ ClassPathXmlApplicationContext 

      1、通过XML中配置 <context:component-scan base-package="com.example.ioc.pojo" /> 扫描路径,

           2、使用方式1加载beans.xml文件,及访问bean对象


    方法3:pojo对象增加@Component注解 + @Configuration类 + @ComponentScan + AnnotationConfigApplicationContext

    通常定义单独的config目录
    @Configuration @PropertySource(
    "classpath:db.properties") @ComponentScan("com.example.ioc.pojo") // 通过扫描方式获取bean定义 public class BeanConfig { }

    解析代码

    AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(BeanConfig.class);
    Book book = annotationConfigApplicationContext.getBean(Book.class);

     

    方法4:pojo对象增加@Component注解 + @Configuration类(内部定义@Bean)  + AnnotationConfigApplicationContext

    @Configuration
    @PropertySource("classpath:db.properties")
    public class BeanConfig {
    
        @Bean
        public Book book() {
            return new Book();
        }
    }

    此时方法名就是bean id

  • 相关阅读:
    虚方法(virtual)和抽象方法(abstract)的区别
    IT社区
    C#中动态加载和卸载DLL
    应用程序体系结构
    Enterprise Architect 7.0入门教程
    jQuery插件开发基础1
    asp.net页面事件执行顺序
    codesmith4.1破解版
    在Web.config配置文件中自定义配置节点
    小巧实用的节拍器软件FineMetronome介绍 原创
  • 原文地址:https://www.cnblogs.com/clarino/p/15481744.html
Copyright © 2011-2022 走看看