建立maven项目
打开pop.xml文件
添加springframework所依赖的包
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.10.RELEASE</version> </dependency>
1、pom.xml文件内容如下
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.fz</groupId> <artifactId>spring01</artifactId> <version>1.0</version> <packaging>jar</packaging> <properties/> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.10.RELEASE</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.18</version> </dependency> </dependencies> <build> <finalName>${project.artifactId}</finalName> <sourceDirectory>src/main/java</sourceDirectory> <testSourceDirectory>src/test/java</testSourceDirectory> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> </includes> </resource> </resources> </build> </project>
2、在src/main/resources 建立
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-4.3.xsd">
<!-- spring框架默认bean的单例模式 --> <bean name="book" class="com.fz.entity.Book"/>
</beans>
3、编写程序要使用的类
src/main/java/com/fz/entity/Book.java package com.fz.entity; import lombok.Data; /** * Created by webrx on 2017-09-07. */ @Data public class Book { private int id; private String name; }
4、测试框架代码
src/test/com/Demo.java package com; import com.fz.entity.Book; import org.junit.Test; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.Date; /** * Created by webrx on 2017-09-07. */ public class Demo { @Test public void tt(){ BeanFactory f = new ClassPathXmlApplicationContext("applicationContext.xml"); //建立bean工厂 Book b = f.getBean(Book.class); Book book = f.getBean("book",Book.class); System.out.println(book); b.setId(100); b.setName("java书籍"); System.out.println(b); System.out.println(b==book); } }