maven中配置spring依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
我们创建一个User类,User类内部依赖一个Account类。
public class User {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
private int age;
private int sex;
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
private Account account;
@Override
public String toString() {
return "account balance is "+this.account.getBalance();
}
}
public class Account {
public float getBalance() {
return balance;
}
public void setBalance(float balance) {
this.balance = balance;
}
public Account(){
this.balance = 30.0f;
}
private float balance;
}
如果不使用依赖注入,我们需要手动new一个Account类,然后通过传递给User类。使用spring后我们可以通过配置spring bean来让容器自动管理这些依赖。下面我们配置一下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 name="user" class="com.hn.spring.User" scope="prototype">
<property name="account" ref="account"/>
</bean>
<bean name="account" class="com.hn.spring.Account" scope="prototype"/>
</beans>
我们配置了user bean的account属性,使用set注入了依赖。我们bascope 设置为prototype,每次都重新实例化对象。
我们编写代码测试一下:
public class TestUser {
@Test
public void testSingletonScope(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User user1 = context.getBean(User.class);
User user2 = context.getBean(User.class);
Assert.assertNotEquals(user1,user2);
}
@Test
public void testProtypeScope(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Account account1 = context.getBean(Account.class);
Account account2 = context.getBean(Account.class);
Assert.assertNotEquals(account1,account2);
}
}
首先我们加载beans.xml用来创建context,然后获取User bean,由于我们设置了原型类型,所以创建的两个对象应该是不同的。