springhello程式
先寫個物體類

配置
pom.xml
匯入lombok純粹是為了省一些寫代碼的操作,使用注解的方式來省下時間,但是初學者還是非常不建議使用這個

導的spring是下面這個mvc的web架構的包,可以使用

里面的包里面有這些分支,可以使用,

<?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是一個物件
id是變數名
class是new的物件
property相當于給物件中的屬性配置一個值
由spring創建的,原來是
物件由spring注冊管理等
-->
<bean id="hello" >
<property name="str" value = "https://www.cnblogs.com/yhycoder/p/hello world"/>
</bean>
<!-- more bean definitions go here -->
</beans>
修改可以直接在xml檔案中修改,其他的不用理了,所謂的IOC就是物件由spring創建、管理、裝配,
核心
查看DeaultListableBeanFactory

IOC(Inversion of Control)
The
org.springframework.beansandorg.springframework.contextpackages are the basis for Spring Framework’s IoC container. --spinng官網上的一句華
直譯過來就是這里兩個包是spring框架中的IOC容器的基礎,在上面的maven截圖中,也是可以看到spring mvc里面有這兩個包,要不然也不可能使用完整的spring框架,所以想學會這個IOC,這兩個包的了解是必不可少的,
IOC創建物件
- 默認是無參構造方法
- 也可以有參構造(也是DI中的構造器注入)
環境
先總體的專案小測配置以及定義的各個類

物體類
package com.yhy.pojo;
public class Hello {
private String str;
public Hello(String str) {
this.str = str;
}
/**
* @return String return the str
*/
public String getStr() {
return str;
}
/**
* @param str the str to set
*/
public void setStr(String str) {
this.str = str;
}
public void show() {
System.out.println(str);
}
}
測驗類
@Test
public void test()
{
//獲得spring的背景關系內容
//拿到容器
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//使用容器獲得物件
Hello hello = (Hello) context.getBean("hello");
hello.show();
}
使用有參構造有幾個方法
在beans.xml中使用三種方式
- 使用引數名
<bean id="hello" >
<constructor-arg name="str" value="https://www.cnblogs.com/yhycoder/p/yhy"/>
</bean>
- 使用下標索引
<bean id="hello" >
<!-- 從零開始的索引值,多個引數的時候再使用別的引數 -->
<constructor-arg index="0" value="https://www.cnblogs.com/yhycoder/p/hello world"/>
</bean>

- 使用引數的型別來配置
<bean id="hello" >
<constructor-arg type="java.lang.String" value="https://www.cnblogs.com/yhycoder/p/hello spring"/>
</bean>

其他
在.xml組態檔中還有兩個選項,

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/179613.html
標籤:Java
