# spring文件創建 ###### tags: `Spring-基礎` ### 1.先創建Moven的Module Moven可以幫忙完成很多工作,後續會再學習補充 ![](https://i.imgur.com/9BF7COi.png) ### 2.創建實體類 以Hello實體類為例 ```java= public class Hello { private String str; public String getStr() { return str; } //Spring調用無參構造器,然後用set注入 public void setStr(String str) { this.str = str; } @Override public String toString() { return "Hello{" + "str='" + str + '\'' + '}'; } } ``` ### 3.創建Spring容器 創建.xml文件 ![](https://i.imgur.com/M528Ey8.png) 需要xml上方先導入spring配置的結構 **可以在Spring官網找到** ```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 http://www.springframework.org/schema/beans/spring-beans.xsd"> ``` 利用Spring創建對象 ```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 http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--使用spring來創建對象,再spring這些都稱為Bean 過去寫法 類型 變量名 = new 類型(): Hello hello = new Hello(); 新寫法 id = 變量名 class = new的對象 property 相當於給對象中的屬性設置一個值 --> <bean id="hello" class="com.kuang.pojo.Hello"> <property name="str" value="Spring"/> </bean> </beans> ``` ### 3.執行 ```java= public class MyTest { public static void main(String[] args) { //獲取Spring的上下文對象 //使用spring配置前,必須要創建這行代碼,"xxx.xml"決定要引入哪份配置 ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); //我們的對象現在都在Spring中的管理了,我們要使用,直接去裡面取出來就可以 //從xml的容器中取出bean元素的"hello"來創建,而非new hello來創建 //使用Spring後,對象由Spring來創建 Hello hello =(Hello) context.getBean("hello"); //Hello{str='Spring'} //因為beans.xml中,<property name="str" value="Spring"/> System.out.println(hello.toString()); } } ``` ### 範例二 #### Spring容器 ```xml= <bean id="mysqlImpl" class="com.kuang.dao.UserDaoMysqlImpl/"> <bean id="UserServiceImpl" class="com.kuang.dao.UserDaoOracleImpl/"> <bean id="UserServiceImpl" class="com.kuang.service.UserServiceImpl"> <!--ref:引用Spring容器中創建好的對象 value:具體的值,基本數據類型 --> <property name="userDao" ref="mysqlImpl"/> </bean> ``` #### 使用Spring容器中的對象 ```java= public class MyTest{ public static void main(String[] args){ //獲取ApplicationContext:拿到spring的容器 ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); //容器在手,天下我有,需要什麼,就直接get什麼 UserServiceImpl userServiceImpl =(UserServiceImpl)context.getBean("UserServiceImpl"); //之後若要取用不同對象中的getUser //只要改寫xml中的<property name="userDao" ref="mysqlImpl"/>的ref對象即可 userServiceImpl.getUser(); } } ```