标签:servlet 位置 lang java类 配置方法 扩展性 上下文 settings iat
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c\:mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change ‘info‘ to ‘debug‘ ###
log4j.rootLogger=off, stdout
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- demo1快速入门 -->
<!-- 通过一个<bean>标签设置类的信息,通过id属性为类起个标识 -->
<bean id="userService" class="lx.test.spring.demo1.HelloServiceImpl">
<!-- 使用<property>标签注入属性:使用这种方式注入的属性必须要有setter方法 -->
<property name="info" value="入门示例"/>
</bean>
</beans>为了测试磁盘路径的资源获取方式 并在工程根目录下新建applicationContext.xml,,如下所示:<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- demo1快速入门 -->
<!-- 通过一个<bean>标签设置类的信息,通过id属性为类起个标识 -->
<bean id="userService" class="lx.test.spring.demo1.HelloServiceImpl">
<!-- 使用<property>标签注入属性:使用这种方式注入的属性必须要有setter方法 -->
<property name="info" value="入门示例(磁盘路径)"/>
</bean>
</beans>HelloServicepackage lx.test.spring.demo1;
/**
* 入门案例
*
*
*/
public interface HelloService {
public void sayHello();
}
HelloServiceImplpackage lx.test.spring.demo1;
/**
* 入门案例的实现类
*/
public class HelloServiceImpl implements HelloService {
private String info;
public void setInfo(String info) {
this.info = info;
}
public void sayHello() {
System.out.println("Hello Spring..." + info);
}
} 新建入门测试类SpringTest1package lx.test.spring.demo1;
import java.io.IOException;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
public class SpringTest1 {
@Test
// 传统方式
public void demo1() {
// 造成程序紧密耦合
HelloService helloService = new HelloServiceImpl();
helloService.sayHello();
}
@Test
// Spring开发
public void demo2() {
// 创建一个工厂类
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
HelloService helloService = (HelloService) applicationContext
.getBean("userService");
helloService.sayHello();
}
@Test
// 加载磁盘路径下的配置文件
public void demo3() {
ApplicationContext applicationContext = new FileSystemXmlApplicationContext(
"applicationContext.xml");
HelloService helloService = (HelloService) applicationContext
.getBean("userService");
helloService.sayHello();
}
@Test
// 使用BeanFactory加载
public void demo4() throws IOException {
// ClassPathResource FileSystemResource 两种方式
// BeanFactory beanFactory = new XmlBeanFactory(new FileSystemResource("applicationContext.xml"));
// Resource resource= new FileSystemResource("applicationContext.xml");
// F:\myEclipse_project\myspring3_day01\applicationContext.xml
// System.out.println(resource.getFile().getAbsolutePath());
BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(
"applicationContext.xml"));
HelloService helloService = (HelloService) beanFactory
.getBean("userService");
helloService.sayHello();
}
}依次测试运行结果如下:<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- demo2 Bean实例化的三种方式 --> <!-- 默认情况下使用的就是无参数的构造方法 --> <bean name="bean1" class="lx.test.spring.demo2.Bean1" /> <!-- 第二种使用静态工厂实例化 --> <bean id="bean2" class="lx.test.spring.demo2.Bean2Factory" factory-method="getBean2" /> <!-- 第三种使用实例工厂实例化 --> <bean id="bean3" factory-bean="bean3Factory" factory-method="getBean3" /> <bean id="bean3Factory" class="lx.test.spring.demo2.Bean3Factory" /> </beans>Bean1
package lx.test.spring.demo2;
/**
* 使用无参数的构造方法实例化
*/
public class Bean1 {
public Bean1() {
System.out.println("Bean1默认的无参构造...");
}
}
Bean2package lx.test.spring.demo2;
/**
* 使用静态工厂方法实例化
*
*/
public class Bean2 {
}
Bean2Factorypackage lx.test.spring.demo2;
/**
* Bean2的静态工厂
*/
public class Bean2Factory {
public static Bean2 getBean2() {
System.out.println("静态工厂获得Bean2的方法...");
return new Bean2();
}
}
Bean3package lx.test.spring.demo2;
/**
* 使用实例工厂实例化
*/
public class Bean3 {
}
Bean3Factorypackage lx.test.spring.demo2;
/**
* 使用实例工厂
*/
public class Bean3Factory {
public Bean3 getBean3() {
System.out.println("Bean3实例工厂的getBean3()方法...");
return new Bean3();
}
}
SpringTest2package lx.test.spring.demo2;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Bean的实例化测试
*/
public class SpringTest2 {
@Test
// 无参数的构造方法实例化
public void demo1() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
Bean1 bean1 = (Bean1) applicationContext.getBean("bean1");
System.out.println(bean1);
}
@Test
// 无参数的构造方法实例化
public void demo2() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
Bean2 bean2 = (Bean2) applicationContext.getBean("bean2");
System.out.println(bean2);
}
@Test
// 无参数的构造方法实例化
public void demo3() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
Bean3 bean3 = (Bean3) applicationContext.getBean("bean3");
System.out.println(bean3);
}
}依次测试结果如下:<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- Bean的作用范围 --> <bean id="customer" class="lx.test.spring.demo3.Customer" scope="prototype" /> <bean id="product" class="lx.test.spring.demo3.Product" init-method="setup" destroy-method="teardown"> <property name="name" value="空调" /> </bean> </beans>Customer
package lx.test.spring.demo3;
public class Customer {
public Customer() {
System.out.println("Customer类被实例化...");
}
}Productpackage lx.test.spring.demo3;
public class Product {
private String name;
public void setName(String name) {
this.name = name;
}
public void setup() {
System.out.println("Product初始化方法执行...");
}
public void teardown() {
System.out.println("Product销毁的方法执行...");
}
@Override
public String toString() {
return "Product [name=" + name + "]";
}
}测试类SpringTest3package lx.test.spring.demo3;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Bean的作用范围
*/
public class SpringTest3 {
@Test
// 测试scope
public void demo1() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
Customer c1 = (Customer) applicationContext.getBean("customer");
System.out.println(c1);
Customer c2 = (Customer) applicationContext.getBean("customer");
System.out.println(c2);
}
@Test
// 测试初始化和销毁方法
public void demo2() {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
Product p1 = (Product) applicationContext.getBean("product");
System.out.println(p1);
applicationContext.close();
}
}运行结果:<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- Bean的生命周期 --> <bean id="customerService" class="lx.test.spring.demo4.CustomerServiceImpl" init-method="setup" destroy-method="teardown"> <property name="name" value="张三" /> </bean> <bean class="lx.test.spring.demo4.MyBeanPostProcessor" /> </beans>CustomerService
package lx.test.spring.demo4;
public interface CustomerService {
public void add();
public void find();
}
CustomerServiceImplpackage lx.test.spring.demo4;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class CustomerServiceImpl implements CustomerService, BeanNameAware,
ApplicationContextAware, InitializingBean, DisposableBean {
private String name;
public void setName(String name) {
System.out.println("第二步:属性的注入.");
this.name = name;
}
public CustomerServiceImpl() {
super();
System.out.println("第一步:实例化类.");
}
public void add() {
System.out.println("添加客户...");
}
public void find() {
System.out.println("查询客户...");
}
public void setBeanName(String name) {
System.out.println("第三步:注入配置的类的名称" + name);
}
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
System.out.println("第四步:注入ApplicationContext" + applicationContext);
}
public void afterPropertiesSet() throws Exception {
System.out.println("第六步:属性的设置后执行...");
}
public void setup() {
System.out.println("第七步:调用手动设置的初始化方法...");
}
public void destroy() throws Exception {
System.out.println("第十步:调用销毁的方法...");
}
public void teardown() {
System.out.println("第十一步:调用手动销毁的方法...");
}
}
MyBeanPostProcessorpackage lx.test.spring.demo4;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class MyBeanPostProcessor implements BeanPostProcessor {
/**
* bean: 实例对象 beanName:在配置文件中配置的类的标识
*/
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("第五步:初始化之前执行...");
return bean;
}
public Object postProcessAfterInitialization(final Object bean,
String beanName) throws BeansException {
System.out.println("第八步:初始化后执行...");
// 动态代理
if (beanName.equals("customerService")) {
Object proxy = Proxy.newProxyInstance(bean.getClass()
.getClassLoader(), bean.getClass().getInterfaces(),
new InvocationHandler() {
// 调用目标方法的时候,调用invoke方法
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
if ("add".equals(method.getName())) {
System.out.println("权限检验...");
Object result = method.invoke(bean, args);
return result;
}
return method.invoke(bean, args);
}
});
return proxy;
}
return bean;
}
}
SpringTest4package lx.test.spring.demo4;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest4 {
@Test
// Bean完整的生命周期
public void demo1() {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
CustomerService customerService = (CustomerService) applicationContext
.getBean("customerService");
customerService.add();
customerService.find();
applicationContext.close();
}
}运行结果:package lx.test.spring.demo5;
public class Car {
private String name;
private Double price;
public Car() {
super();
}
public Car(String name, Double price) {
super();
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "Car [name=" + name + ", price=" + price + "]";
}
}
Car2package lx.test.spring.demo5;
public class Car2 {
private String name;
private Double price;
public void setName(String name) {
this.name = name;
}
public void setPrice(Double price) {
this.price = price;
}
@Override
public String toString() {
return "Car2 [name=" + name + ", price=" + price + "]";
}
}
Personpackage lx.test.spring.demo5;
public class Person {
private String name;
private Car2 car2;
public void setName(String name) {
this.name = name;
}
public void setCar2(Car2 car2) {
this.car2 = car2;
}
@Override
public String toString() {
return "Person [name=" + name + ", car2=" + car2 + "]";
}
}
PersonInfopackage lx.test.spring.demo5;
public class PersonInfo {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String showName() {
return name;
}
}
applicationContext.xml<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Bean的属性注入 -->
<!-- 构造方法注入 -->
<bean id="car1_01" class="lx.test.spring.demo5.Car">
<constructor-arg name="name" value="宝马" />
<constructor-arg name="price" value="1000000" />
</bean>
<bean id="car1_02" class="lx.test.spring.demo5.Car">
<constructor-arg index="0" type="java.lang.String"
value="奔驰" />
<constructor-arg index="1" type="java.lang.Double"
value="2000000" />
</bean>
<!-- setter方法: <property>或p名称空间 -->
<bean id="car2_01" class="lx.test.spring.demo5.Car2">
<property name="name" value="五菱"/>
<property name="price" value="10000"/>
</bean>
<bean id="car2_02" class="lx.test.spring.demo5.Car2">
<property name="name" value="#{‘开瑞优优‘}"/>
<property name="price" value="#{8000}"/>
</bean>
<bean id="car2_03" class="lx.test.spring.demo5.Car2" p:name="面包车" p:price="15000"/>
<!-- ref:注入成员对象 -->
<bean id="person_01" class="lx.test.spring.demo5.Person">
<property name="name" value="老子"/>
<property name="car2" ref="car2_01"/>
</bean>
<!-- p命名空间写法 -->
<bean id="person_02" class="lx.test.spring.demo5.Person" p:name="上帝" p:car2-ref="car2_02"/>
<!-- SPEL写法 -->
<bean id="person_03" class="lx.test.spring.demo5.Person">
<property name="name" value="#{personInfo.showName()}"/>
<property name="car2" value="#{car2_03}"/>
</bean>
<bean id="personInfo" class="lx.test.spring.demo5.PersonInfo">
<property name="name" value="张三"/>
</bean>
</beans>SpringTest5package lx.test.spring.demo5;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest5 {
@Test
public void demo1() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
Car car = (Car) applicationContext.getBean("car1_01");
Car car1_02 = (Car) applicationContext.getBean("car1_02");
System.out.println(car);
System.out.println(car1_02);
}
@Test
public void demo2() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
Car2 car2_01 = (Car2) applicationContext.getBean("car2_01");
Car2 car2_02 = (Car2) applicationContext.getBean("car2_02");
Car2 car2_03 = (Car2) applicationContext.getBean("car2_03");
System.out.println(car2_01);
System.out.println(car2_02);
System.out.println(car2_03);
}
@Test
public void demo3() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
Person person_01 = (Person) applicationContext.getBean("person_01");
Person person_02 = (Person) applicationContext.getBean("person_02");
Person person_03 = (Person) applicationContext.getBean("person_03");
System.out.println(person_01);
System.out.println(person_02);
System.out.println(person_03);
}
}
运行结果如下:package lx.test.spring.demo6;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class CollectionBean {
private List<String> list;
private Set<String> set;
private Map<String, Integer> map;
private Properties properties;
public void setList(List<String> list) {
this.list = list;
}
public void setSet(Set<String> set) {
this.set = set;
}
public void setMap(Map<String, Integer> map) {
this.map = map;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
@Override
public String toString() {
return "CollectionBean [list=" + list + ",\n set=" + set + ",\n map=" + map
+ ",\n properties=" + properties + "]";
}
}
SpringTest6package lx.test.spring.demo6;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest6 {
@Test
public void demo1(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
CollectionBean collectionBean = (CollectionBean) applicationContext.getBean("collectionBean");
System.out.println(collectionBean);
}
}
applicationContext.xml<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <import resource="classpath:applicationContext2.xml" /> </beans>applicationContext2.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 集合属性的注入 --> <bean id="collectionBean" class="lx.test.spring.demo6.CollectionBean"> <!-- 注入List集合 --> <property name="list"> <list> <value>武藤兰</value> <value>桐谷静香</value> </list> </property> <!-- 注入Set集合 --> <property name="set"> <set> <value>小泽</value> <value>苍老师</value> </set> </property> <!-- 注入Map集合 --> <property name="map"> <map> <entry key="小咪咪" value="123" /> <entry key="小胡子 " value="456" /> </map> </property> <property name="properties"> <props> <prop key="username">root</prop> <prop key="password">123456</prop> </props> </property> </bean> </beans>运行测试类
package spring3.annotation.demo1;
import org.springframework.stereotype.Repository;
@Repository("userDao")
public class UserDao {
}
UserServicepackage spring3.annotation.demo1;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
/**
* 注解的方式装配Bean
*/
// @Component、@Service以及@Repository的功能就是注册Bean类
// 相当于XML中的如下配置
// <bean id="userService" class="spring3.annotation.demo1.UserService" />
// @Component(value = "userService")
@Service
@Scope
public class UserService {
// @Value注解是注入Bean类中的普通属性 相当于XML中的<property name="" value="">
@Value(value = "annotationInfo")
private String info;
// @Autowired(required=true)
// @Qualifier("userDao")
// 注意:@Autowired和@Qualifier结合相当于@Resource
@Resource(name = "userDao")
private UserDao userDao;
public void sayHello() {
System.out.println("Hello Spring Annotation..." + info);
}
@PostConstruct
// @PostConstruct相当于 XML中<bean> 的属性 init-method=""
public void setup() {
System.out.println("初始化...");
}
@PreDestroy
// @PreDestroy相当于XML中<bean>的属性 destroy-method=""
public void teardown() {
System.out.println("销毁...");
}
}
SpringTest1package spring3.annotation.demo1;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
// 注解的方式
public class SpringTest1 {
@Test
public void demo1() {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
UserService userService = (UserService) applicationContext
.getBean("userService",UserService.class);
System.out.println(userService);
UserService userService2 = (UserService) applicationContext
.getBean("userService",UserService.class);
System.out.println(userService2);
applicationContext.close();
}
}
applicationContext.xml<?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="spring3.annotation.demo1" /> </beans>注意:<context:component-scan base-package="">会扫描当前包下的所有类的注解以及所有子包的类注解。
package spring3.annotation.demo2;
public class Car {
private String name;
private Double price;
public void setName(String name) {
this.name = name;
}
public void setPrice(Double price) {
this.price = price;
}
@Override
public String toString() {
return "Car [name=" + name + ", price=" + price + "]";
}
}
Productpackage spring3.annotation.demo2;
public class Product {
private String name;
private Double price;
public void setName(String name) {
this.name = name;
}
public void setPrice(Double price) {
this.price = price;
}
@Override
public String toString() {
return "Product [name=" + name + ", price=" + price + "]";
}
}
BeanConfigpackage spring3.annotation.demo2;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class BeanConfig {
@Bean(name = "car")
public Car showCar() {
Car car = new Car();
car.setName("大众");
car.setPrice(200000d);
return car;
}
@Bean(name = "product")
public Product initProduct() {
Product product = new Product();
product.setName("空调");
product.setPrice(3000d);
return product;
}
}
applicationContext.xml<?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="spring3.annotation.demo2" /> </beans>SpringTest2
package spring3.annotation.demo2;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest2 {
@Test
// 加载XML配置文件 (配置了进行自动扫描注解类)
public void demo1() {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
Car car = (Car) applicationContext.getBean("car");
Product product = (Product) applicationContext.getBean("product");
System.out.println(car);
System.out.println(product);
}
@Test
// 不使用Spring的配置文件,手动注册config类
public void demo2() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.register(BeanConfig.class);
applicationContext.refresh(); // 刷新容器以应用这些注册的配置类
Car car = (Car) applicationContext.getBean("car");
Product product = (Product) applicationContext.getBean("product");
System.out.println(car);
System.out.println(product);
}
}
运行结果:package spring3.annotation.demo3;
public class CustomerDao {
}
OrderDaopackage spring3.annotation.demo3;
public class OrderDao {
}
CustomerServicepackage spring3.annotation.demo3;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class CustomerService {
private CustomerDao customerDao;
@Autowired
@Qualifier("orderDao")
private OrderDao orderDao;
public void setCustomerDao(CustomerDao customerDao) {
this.customerDao = customerDao;
}
@Override
public String toString() {
return "CustomerService [customerDao=" + customerDao + ", orderDao="
+ orderDao + "]";
}
}
applicationContext2.xml<?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config /> <bean id="customerDao" class="spring3.annotation.demo3.CustomerDao" /> <bean id="orderDao" class="spring3.annotation.demo3.OrderDao" /> <bean id="customerService" class="spring3.annotation.demo3.CustomerService"> <property name="customerDao" ref="customerDao" /> <!-- <property name="orderDao" ref="orderDao" /> --> </bean> </beans>SpringTest3
package spring3.annotation.demo3;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest3 {
@Test
public void demo1() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext2.xml");
CustomerService customerService = (CustomerService) applicationContext
.getBean("customerService");
System.out.println(customerService);
}
}
运行结果如下:package spring3.web.service;
public class UserService {
public void sayHello() {
System.out.println("Hello Spring web...");
}
}
UserServletpackage spring3.web.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import spring3.web.service.UserService;
public class UserServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");*/
WebApplicationContext applicationContext=WebApplicationContextUtils.getWebApplicationContext(getServletContext());
UserService userService=(UserService) applicationContext.getBean("userService");
userService.sayHello();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>spring3.web.servlet.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/user</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>applicationContext.xml<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="userService" class="spring3.web.service.UserService" /> </beans>log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c\:mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change ‘info‘ to ‘debug‘ ###
log4j.rootLogger=info, stdout 访问Servlet 后台打印如下:package spring3.web.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import spring3.web.service.UserService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class SpringTest {
@Autowired
private UserService userService;
@Test
public void demo1() {
userService.sayHello();
}
}
运行结果如下:JAVAWEB开发之Spring详解之——Spring的入门以及IOC容器装配Bean(xml和注解的方式)、Spring整合web开发、整合Junit4测试
标签:servlet 位置 lang java类 配置方法 扩展性 上下文 settings iat
原文地址:http://blog.csdn.net/u013087513/article/details/70147024