1。匯入依賴包
匯入Spring依賴包,日誌使用Log4j2
<?xml version=“1。0” encoding=“UTF-8”?>
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程式