标签:1.0 工厂 编程 spring ase group get his 项目
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.3.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.3.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>4.3.7.RELEASE</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies>
UserService
public interface UserService { public void sayHello(); }
UserServiceImpl
public class UserServiceImpl implements UserService{ public String getName() { return name; } public void setName(String name) { this.name = name; } //添加属性 private String name; @Override public void sayHello() { System.out.print("hello spring" + name); } }
SpringDemo1
public class SpringDemo1 { @Test /** * 传统方式开发 */ public void demo1(){ //UserService userService = new UserServiceImpl(); UserServiceImpl userService = new UserServiceImpl(); //设置属性 传统方法要改代码 就不好了 userService.setName("张三"); userService.sayHello(); } @Test /** * 使用Spring 的方式 */ public void demo2(){ //创建Spring的工厂 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); //通过工厂获得类 UserService userService = (UserService) applicationContext.getBean("userService"); userService.sayHello(); } }
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"> <!-- UserService的创建权交给了Spring--> <bean id="userService" class="com.windbag.ioc.demo1.UserServiceImpl"> <!-- 设置属性--> <property name="name" value="李四"></property> </bean> </beans>
标签:1.0 工厂 编程 spring ase group get his 项目
原文地址:https://www.cnblogs.com/windbag7/p/9542300.html