基础开发步骤
基础开发步骤
一、创建Mavan工程聚合和子模块
创建项目,删除src文件夹,新建子模块。
该步骤在个人开发中并不被认为是一个必须的步骤,它往往只在大型项目中有必要。
二、引入Spring依赖
打开pom.xml文件引入Spring依赖。
| <dependencies>
<!-- 规定依赖写在该标签中,并按照下列格式书写 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context </artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
</dependency>
<!-- 或者使用下列方案 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
|
三、编写程序
通常,代码写在/src/main/java目录下。
需要使用bean进行管理的类,需要在类前一行使用@Component声明。
| package online.umbracore.blog;
import org.springframework.stereotype.Component;
@Component
public class User {
public void add(){
System.out.println("add...");
}
}
|
五、测试
1.在写好的类名上Shift+Ctrl+T 新建测试类;
2.在测试类中创建方法进行测试。测试方法的方法体如下:
| @SpringBootTest
//该注解必须写,否则无法创建Spring容器进行测试
class BlogApplicationTests {
//创建Bean管理的类对象
//Autowired代表该对象属于Bean管理的类,框架会自行注入
//该过程执行了无参构造函数,使用了反射进行创建对象
//使用Autowired声明的对象禁止使用new进行初始化
@Autowired
public User user;
//在使用包含bean管理的类对象的方法时,需要用GetMapping()声明该方法的路径
//参数为方法相对于bean管理的对象的路径
@GetMapping("/add")
public void userAdd(){
user.add();
}
}
|
分析
1.由bean管理的对象都使用单例模式,无论在实际应用中创建多少次对象,都始终只会调用一次构造函数。
2.由bean管理的对象在创建时调用类的无参构造函数。
3.spring框架根据类的全路径,使用反射创建对象。
| //示例
Class clazz =Class.forName("oline.umbracore.blog.User");
//调用方法创建对象
//Object o=clazz.newInstance();
//使用反射创建对象时返回的是一个超类(Object),需要强制转换为需要的类型
User user=(User)clazz..getDeclaredConstructor().newInstance();
|
4.创建后的对象被放在DefaultListableBeanFactory类中的beanDefinitionMap,原型:
| private final Map<String, BeanDefinition> beanDefinitionMap;
|