1. In the last lecture, we used the Spring container to manage Bean objects in the form of XML configuration files, and finally gave a thought question: "If we have dozens of classes to create Beans, using XML configuration, will Spring configure The file seems bloated, how to solve this problem?" In this lecture, we plan to use component annotations to streamline Spring configuration files.
2. Use component annotations to streamline the Spring configuration file
1. Create the net.tjl.spring.lesson02 package
2. Copy the four classes of the lesson01 sub-package to the lesson02 sub-package
3. Modify the dragon-killing task class-SlayDragonQuest
5. Modify the brave knight Class-BraveKnight
6. Modify the rescue knight class-DamselRescuingKnight
7. Create a Spring configuration file
. Create an xml_annotation subdirectory in the resources directory, and then create a Spring configuration file in it-spring-config.xml
8. Create a test class-TestKnight
in test/ Create the net.tjl.spring.lesson2 package in java, and create the TestKnight class in the package
package net.tjl.spring.lesson02;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* 功能:测试骑士类
* 作者:谭金兰
* 日期:2021年03月17日
*/
public class TestKnight {
private ClassPathXmlApplicationContext context;
@Before
public void init() {
// 基于Spring配置创建应用容器
context = new ClassPathXmlApplicationContext("xml_annotation/spring-config.xml");
}
@Test
public void testBraveKnight() {
// 根据名称从应用容器里获取勇敢骑士对象
BraveKnight braveKnight = (BraveKnight) context.getBean("braveKnight");
// 勇敢骑士执行任务
braveKnight.embarkOnQuest();
}
@Test
public void testDamselRescuingKnight() {
// 根据名称从应用容器里获取拯救少女骑士对象
DamselRescuingKnight damselRescuingKnight = (DamselRescuingKnight) context.getBean("damselRescuingKnight");
// 拯救少女骑士执行任务
damselRescuingKnight.embarkOnQuest();
}
@After
public void destroy() {
// 关闭应用容器
context.close();
}
}
. Run the test method testBraveKnight() to view the results
. Run the test method testDamselRescuingKnight() to view the results.
Run the entire test class and view the effect.
9. How to implement a custom bean name.
Run the test method testBraveKnight() to view the results.
4. Program optimization- Orientation Interface
1. Create task interface-Quest
2. Create knight interface-Knight
3. Modify the dragon-killing task class-SlayDragonQuest
4. Modify the rescue character class-RescueDamselQuest
5. Modify the brave knight class-BraveKnight
6. Modify the rescue knight class-DamselRescuingKnight
7. Run the test class-TestKnight