Spring配置元数据的三种方式

做了一年多的程序员,很多东西都只是会用,知其然而不知其所以然。决定学习一下,买了一本spring入门经典,从头开始学,仅做个人学习笔记,有不对的地方欢迎指正。最近响应国家号召发展地摊经济,更新可能比较慢-,-
这是第二章依赖注入的第一个练习,主要讲解spring三种配置元数据的方式,一种是基于java类配置。一种是基于xml配置,还有一种最常用的基于注解配置。
项目结构:
Spring配置元数据的三种方式_第1张图片
main函数:

    public static void main( String[] args ){
//基于java类配置元数据
//      AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Ch2BeanConfiguration.class);
//基于xml配置元数据    使用ch2-beans.xml
//    	ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("/com/wiley/beginningspring/ch2-beans.xml");
//基于注解配置元数据    使用ch22-beans.xml
    	ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("/com/wiley/beginningspring/ch22-beans.xml");
        AccountService accountService = applicationContext.getBean("accountService",AccountService.class);
        System.out.println("转账之前");
        System.out.println("一号账户"+accountService.getAccount(1).getBalance());
        System.out.println("二号账户"+accountService.getAccount(2).getBalance());
        accountService.transferMoney(1, 2, 5.0);
        System.out.println("转账后");
        System.out.println("一号账户"+accountService.getAccount(1).getBalance());
        System.out.println("二号账户"+accountService.getAccount(2).getBalance());

    }

各个类的代码

public class Account {
	private long id;
	private String ownername;
	private double balance;
	private Date accessTime;
	private boolean locked;
	
	//get    set     方法
	
}
public interface AccountDao {
	public void insert(Account account);
	public void update(Account account);
	public void update(List<Account> accounts);
	public void delete(long accountId);
	public Account find(long accountId);
	public List<Account> find(List<Long> accountIds);
	public List<Account> find(String ownername);
	public List<Account> find(boolean locked);
}

public interface AccountService {
	public void transferMoney(long sourceAccountId,long targetAccountId,double amount);
	public void depositMoney(long accountId,double amount)throws Exception;
	public Account getAccount(long accountId);
}

@Service//基于注解的配置
public class AccountServiceImpl implements AccountService {
	@Autowired//基于注解的配置,也可以放在下面的set方法上面
	private AccountDao accountDao;
	//setter注入,最末尾记录一下构造函数注入与setter注入的区别
	public void setAccountDao(AccountDao accountDao) {
		this.accountDao = accountDao;
	}
	//如果使用构造函数注入就生命一个下面这种构造函数,并且修改ch2-beans.xml
	//public AccountServiceImpl(AccountDao accountDao) {
	//	this.accountDao = accountDao;
	//}
	
	public void transferMoney(long sourceAccountId, long targetAccountId, double amount) {
		Account sourceAccount = accountDao.find(sourceAccountId);
		Account targetAccount = accountDao.find(targetAccountId);
		sourceAccount.setBalance(sourceAccount.getBalance()-amount);
		targetAccount.setBalance(targetAccount.getBalance()+amount);
		accountDao.update(sourceAccount);
		accountDao.update(targetAccount);
		
	}

	public void depositMoney(long accountId, double amount) throws Exception {
		Account account = accountDao.find(accountId);
		account.setBalance(account.getBalance()+amount);
		accountDao.update(account);
		
	}

	public Account getAccount(long accountId) {
		return accountDao.find(accountId);
	}

}

@Repository//基于注解的配置
public class AccountDaoInMemoryImpl implements AccountDao{
	
	private Map<Long, Account> accountsMap = new HashMap<Long, Account>(); 
	{
		Account account1 = new Account();
		account1.setId(1l);
		account1.setOwnername("John");
		account1.setBalance(10.0);
		
		Account account2 = new Account();
		account2.setId(2l);
		account2.setOwnername("Mary");
		account2.setBalance(20.0);
		
		accountsMap.put(account1.getId(), account1);
		accountsMap.put(account2.getId(), account2);
	}
	public void insert(Account account) {
		accountsMap.put(account.getId(), account);
		
	}

	public void update(Account account) {
		accountsMap.put(account.getId(), account);
	}

	public void update(List<Account> accounts) {
		for(int i = 0;i < accounts.size();i++) {
			accountsMap.put(accounts.get(i).getId(), accounts.get(i));
		}
	}

	public void delete(long accountId) {
		accountsMap.remove(accountId);
	}

	public Account find(long accountId) {
		return accountsMap.get(accountId);
	}

	public List<Account> find(List<Long> accountIds) {
		List<Account> list = new ArrayList<Account>();
		for(int i = 0;i < accountIds.size();i++) {
			list.add(accountsMap.get(accountIds.get(i)));
		}
		return list;
	}

	public List<Account> find(String ownername) {
		List<Account> list = new ArrayList<Account>();
		for (Entry<Long, Account> entry : accountsMap.entrySet()) {  
			if(ownername.equals(entry.getValue().getOwnername())){  
                list.add(entry.getValue());
            }  
        }
		return list;
	}

	public List<Account> find(boolean locked) {
		List<Account> list = new ArrayList<Account>();
		for (Entry<Long, Account> entry : accountsMap.entrySet()) {  
			if(locked == entry.getValue().isLocked()){  
                list.add(entry.getValue());
            }  
        }
		return list;
	}

}
//基于java的Bean定义类
@Configuration
public class Ch2BeanConfiguration {
	
	@Bean
	public AccountService accountService() {
		AccountServiceImpl bean = new AccountServiceImpl();
		bean.setAccountDao(accountDao());
		return bean;
	}
	
	@Bean
	public AccountDao accountDao() {
		AccountDaoInMemoryImpl bean = new AccountDaoInMemoryImpl();
		return bean;
	}
}

ch2-beans.xml代码:

<?xml version="1.0" encoding="UTF-8"?>
://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">
	
	>
	<!-- setter注入 -->
		
	<!-- 构造函数注入 -->
	
	
			
>

ch22-beans.xml代码

<?xml version="1.0" encoding="UTF-8"?>
://www.springframework.org/schema/beans"
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xmlns:context="http://www.springframework.org/schema/context"
		xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-4.0.xsd">
	<!-- 开启注解,并且允许自定义bean -->
	
>

基于Java类配置时,不论调用多少次accountDao()方法,Spring都会默认返回同一个Bean。
setter注入在Bean实例化之后执行,构造函数注入在组件创建时执行。
构造函数无法处理循环依赖,setter注入可以。
当使用构造函数注入时,如果有两个构造函数,参数相同,参数位置不同时,需要使用index,否则无法创建Bean实例。

<constructor-arg ref="aclass" index="0"/>

你可能感兴趣的:(Spring入门经典学习记录)