要学习Spring,在理解了依赖注入以及Spring 对依赖注入是怎么实现的,之后,我们首先要学习的是如何使用Spring
要使用Spring就要把我们的bean交给Spring IOC容器来管理,所以首先我们要来做容器的配置。
示例代码如下:
HelloWrold.java
public class HelloWorld {
private String username;
private int age;
public void sayhello(){
System.out.println("Hello World " + username + ",age: " + age);
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
传统的调用方式:
@Test
void testOld() throws Exception{
HelloWorld helloWorld= new HelloWorld();
helloWorld.setUsername("qiaog");
helloWorld.sayhello();
}
使用spring以后的调用方式:
- applicationContext.xml配置文件
<bean id="helloWorld" class="com.qiaog.hello.HelloWorld">
<property name="username" value="qiaog"/>
<property name="age" value="17"/>
</bean>
- 使用Spring来调用
@Test
void testIoc() throws Exception{
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld helloWorld = applicationContext.getBean("helloWorld",HelloWorld.class);
helloWorld.sayhello();
}