通過實例解析Spring Ioc項目實現過程
0. Ioc
https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html
主要是實現一個控制反轉,耦合性大大降低。
1. 建maven項目
建立一個空的maven項目,然后pom.xml添加spring-context的依賴:
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.7.RELEASE</version> </dependency>
2. 創建pojo java對象
package com.aca;public class Hello { private String str; public void setStr(String str) { this.str = str; } public String getStr() { return str; } public Hello(String str){ this.str = str; } @Override public String toString() { return 'Hello{' +'str=’' + str + ’’’ +’}’; }}
3. 創建bean xml配置元數據
配置文件放在resources下。這里以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 https://www.springframework.org/schema/beans/spring-beans.xsd'> <bean class='com.aca.Hello'> <constructor-arg type='java.lang.String' value='fffff'/> </bean></beans>
如果有多個resource或者目錄不一致,就需要import一下:
<beans> <import resource='services.xml'/> <import resource='resources/messageSource.xml'/> <import resource='/resources/themeSource.xml'/> <bean /> <bean /></beans>
里面可以調用構造函數來初始化一下bean。
4.創建spring 上下文
這里用ClassPathXmlApplicationContext 方法。
ApplicationContext context = new ClassPathXmlApplicationContext('hbean.xml');// retrieve configured instance Hello hello = context.getBean('Hello', Hello.class);// hello.setStr('abc'); System.out.println(hello);
直接可以用這個bean,由xml注入。
5. Error:java: 錯誤: 不支持發行版本 5
將file- project structure 中的jdk版本選成跟本地一直,比如我這個jdk14
將build -> java complier中的兩個版本選擇成跟本地一致,這里是14
這兩步做好以后不會報錯,maven里面不需要選擇版本。
6. 如果報xml的問題
xml declaration should precede all document
那是因為xml 第一行是空格了,必須<?xml 做為第一行。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
