早前跟著馬士兵老師的視頻學習了一下spring契吉,動手比較少,沒什么深刻的理解诡渴。今天開始從頭下手對spring了解一下捐晶。
代碼結構如下:
image.png
public class HelloWorld {
private String name;
public void setname(String name) {
System.out.println("setname:"+name);
this.name=name;
}
public void hello(){
System.out.println("hello "+name);
}
public HelloWorld(){
System.out.println("hello world construct");
}
}
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
//HelloWorld hellow= new HelloWorld();
//hellow.setname("Spring test");
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
//HelloWorld hellow = (HelloWorld)ctx.getBean("helloWorld");
//hellow.hello();
}
}
bean.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-2.0.xsd">
<bean id="helloWorld" class="com.lyc.spring.HelloWorld">
<property name="name" value="Spring_HelloWorld"></property>
</bean>
</beans>
輸出結果看spring完成的class的實例化,構造函數(shù)。接下來就能直接調(diào)用了惑灵。
這樣就引入了控制反轉IOC:
傳統(tǒng)都是new一個對象出來調(diào)用∩缴希現(xiàn)在交給了Spring容器創(chuàng)建需要的對象。通俗來講有個司機開車需要自己動手英支,控制反轉就是自己不動手開車佩憾,而是設置程序自動駕駛