【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

原文地址:https://www.cnblogs.com/clarino/p/15481744.html