@Configuration、@Bean以及Bean注册的多种方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/daijiguo/article/details/84847486

Bean的定义:

java方式:

@Configuration和@Bean的配合使用

xml方式:

<beans><bean><bean><beans>
仅有上述步骤,只是完成了Bean的定义,Bean还没有被真正注册到Spring容器中。


Bean的注册:

java方式:

通过AnnotationConfigApplicationContext类实现,示例代码如下:

@Configuration
public class AppContext {
    @Bean
    public Course course() {
        Course course = new Course();
        course.setModule(module());
        return course;
    }
 
    @Bean
    public Module module() {
        Module module = new Module();
        module.setAssignment(assignment());
        return module;
    }
 
    @Bean
    public Assignment assignment() {
        return new Assignment();
    }
}
public static void main(String[] args) {
  ApplicationContext ctx = new AnnotationConfigApplicationContext(AppContext.class);
  Course course = ctx.getBean(Course.class);
  course.getName();
}

xml方式:

通过ClassPathXmlApplicationContext类实现,示例代码如下:

<beans>
    <bean id="course" class="demo.Course">
        <property name="module" ref="module"/>
    </bean>
     
    <bean id="module" class="demo.Module">
        <property name="assignment" ref="assignment"/>
    </bean>
     
    <bean id="assignment" class="demo.Assignment" />
</beans>
public static void main(String[] args) {
	ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/*.xml");
	Module module = (Module)context.getBean("module");
}

spring mvc方式:

spring web中,默认上下文是XmlWebApplicationContext,因此您永远不必在您的 web.xml 文件中显式指定这个上下文类。

参考:
https://www.ibm.com/developerworks/cn/webservices/ws-springjava/index.html

猜你喜欢

转载自blog.csdn.net/daijiguo/article/details/84847486