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

  • 相关阅读:
    LeetCode刷题之字符串
    LeetCode刷题之数组复习
    为什么要用移码来表示阶码(指数)呢?
    字节左移跟右移
    一个有趣的问题
    为什么对数组名取地址,得到的为整个数组的地址?
    在win10 64位下搭建汇编环境
    windows切换samba账号进行连接
    samba服务配置记录
    subversion钩子函数使用记录
  • 原文地址:https://www.cnblogs.com/clarino/p/15481744.html
Copyright © 2011-2022 走看看