三、HelloSpring
目錄:導(dǎo)入jar包、代碼編寫、修改案例
1.導(dǎo)入jar包
注:Spring需要導(dǎo)入commons-logging進(jìn)行日志記錄,可以利用maven,它會(huì)自動(dòng)下載對(duì)應(yīng)的依賴項(xiàng)。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.8</version>
</dependency>
2.代碼編寫
1)編寫一個(gè)Hello實(shí)體類。
public class Hello {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show() {
System.out.println("Hello,"+ name );
}
}
2)編寫spring文件,這里先命名為beans.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">
<!--bean就是java對(duì)象,由Spring創(chuàng)建和管理-->
<bean id="hello" class="com.ping.pojo.Hello">
<property name="name" value="Spring"/>
</bean>
</beans>
3)測(cè)試。
@Test
public void test(){
//解析beans.xml文件,生成管理相應(yīng)的Bean對(duì)象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//getBean:參數(shù)即為spring配置文件中bean的id
Hello hello = (Hello) context.getBean("hello");
hello.show();
}
思考
1)Hello對(duì)象是誰創(chuàng)建的?
Hello對(duì)象是由Spring創(chuàng)建的。
2)Hello對(duì)象的屬性是怎么設(shè)置的?
Hello對(duì)象的屬性是由Spring容器設(shè)置的。
3)控制反轉(zhuǎn):
①控制:誰來控制對(duì)象的創(chuàng)建,傳統(tǒng)應(yīng)用程序的對(duì)象是由程序本身控制創(chuàng)建的。使用Spring后,對(duì)象是由Spring來創(chuàng)建的。
②反轉(zhuǎn):程序本身不創(chuàng)建對(duì)象 , 而變成被動(dòng)的接收對(duì)象。
4)依賴注入:就是利用set方法來進(jìn)行注入的。
IoC是一種編程思想,由主動(dòng)的編程變成被動(dòng)的接收。
可以通過newClassPathXmlApplicationContext去瀏覽一下底層源碼。
3.修改案例
1)新增一個(gè)Spring配置文件beans.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">
<bean id="MysqlImpl" class="com.ping.dao.impl.UserDaoMySqlImpl"/>
<bean id="OracleImpl" class="com.ping.dao.impl.UserDaoOracleImpl"/>
<bean id="ServiceImpl" class="com.ping.service.impl.UserServiceImpl">
<!--這里的name并不是屬性,而是set方法后面的那部分,首字母小寫-->
<!--ref:引用Spring中創(chuàng)建好的對(duì)象。value:具體的值,基本數(shù)據(jù)類型。
引用另外一個(gè)bean,不是用value而是用ref。-->
<property name="userDao" ref="OracleImpl"/>
</bean>
</beans>
2)測(cè)試。
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserServiceImpl serviceImpl = (UserServiceImpl) context.getBean("ServiceImpl");
serviceImpl.getUser();
}
到現(xiàn)在徹底不用再程序中去改動(dòng)了,要實(shí)現(xiàn)不同的操作,只需要在xml配置文件中進(jìn)行修改。所謂的IoC就是對(duì)象由Spring來創(chuàng)建、管理、裝配。