Spring在簡單App中的使用

1。匯入依賴包

匯入Spring依賴包,日誌使用Log4j2

<?xml version=“1。0” encoding=“UTF-8”?> spring-ioc org。poiuy 1。0-SNAPSHOT 4。0。0 spring-ioc-useapp 11 11 org。springframework spring-beans 5。2。15。RELEASE org。springframework spring-context 5。2。15。RELEASE org。apache。logging。log4j log4j-core 2。14。1

2。新增配置檔案

在Resources目錄下新增Spring配置檔案,配置檔案中使用context:component-scan指定掃描的包

<?xml version=“1。0” encoding=“UTF-8”?> <!——包掃描——>

3。注入Bean

新增Service介面,定義介面功能

public interface HelloService { String hello();}

實現介面,並使用@Service註解注入到Spring中

@Service(“helloService”)public class HelloServiceImpl implements HelloService { @Override public String hello() { return “Hello Spring”; }}

4。使用Spring

在App中使用Spring

public class SpringUseAppApplication { private static final Logger logger = LogManager。getLogger(SpringUseAppApplication。class); public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext(“classpath:spring/ApplicationContext-Bean。xml”); HelloService helloService = (HelloService) context。getBean(“helloService”); logger。debug(“執行HelloService方法:{}”,helloService。hello()); }}

5。執行

直接執行Application程式

Spring在簡單App中的使用