标签:
Spring通过一个配置文件描述Bean及Bean直接的依赖关系,利用Java语言的反射功能实例化Bean并建立Bean之间的依赖关系。Sprig的IoC容器在完成这些底层工作的基础上,还提供了Bean实例缓存、生命周期管理、Bean实例代理、事件发布、资源装载等高级服务。
<?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="car" class="com.reflect.Car" p:brand="迈锐宝" p:color="黑色" p:maxSpeed="300"/> </beans>
BeanFactoryTest:
package com.beanfactory; import com.reflect.Car; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import java.io.IOException; /** * Created by gao on 16-3-18. */ public class BeanFactoryTest { public static void main(String[] args) throws IOException { ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource res = resolver.getResource("classpath:beans.xml"); BeanFactory bf = new XmlBeanFactory(res); System.out.println("init BeanFactory."); Car car = bf.getBean("car", Car.class); System.out.println("car bean is ready for use!"); } }
log4j.rootLogger=INFO,A1 log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%d %5p [%t] (%F:%L) - %m%n
package com.context; import com.reflect.Car; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.context.annotation.Bean; /** * Created by gao on 16-3-18. */ @Configurable public class Beans { @Bean(name = "car") public Car buildCar() { Car car = new Car(); car.setBrand("英菲迪尼"); car.setMaxSpeed(300); return car; } }
AnnotationApplicationContext:
package com.context; import com.reflect.Car; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * Created by gao on 16-3-18. */ public class AnnotationApplicationContext { public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(Beans.class); Car car = ctx.getBean("car", Car.class); System.out.println(car.getBrand()); System.out.println(car.getMaxSpeed()); } }
BeanFactory 和 ApplicationContext
标签:
原文地址:http://www.cnblogs.com/yangyquin/p/5293420.html