Spring入门(8)-基于Java配置而不是XML

Spring入门(8)-基于Java配置而不是XML

本文介绍如何应用Java配置而不是通过XML配置Spring。

0. 目录

  1. 声明一个简单Bean
  2. 声明一个复杂Bean

1. 声明一个简单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"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 	
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-3.0.xsd"
	>
	<context:component-scan base-package="com.chzhao.springtest"/>
</beans>

声明一个配置类

package com.chzhao.springtest;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyConfig {
	@Bean
	public App app1() {
		return new App();
	}
}

通过@Configuration声明配置类,通过@Bean声明Bean。其中app1就是Bean的ID。
可以通过这个app1值机获得Bean

package com.chzhao.springtest;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
	public static void main(String[] args) {
		@SuppressWarnings("resource")
		ApplicationContext act = new ClassPathXmlApplicationContext(
				"applicationContext.xml");		
		App a = (App) act.getBean("app1");
		a.showMsg();
	}
}

2. 声明一个复杂Bean

如果一个Bean的定义基于另外一个Bean,也很容易实现。
首先看app定义

package com.chzhao.springtest;

public class App {
	public App(IPersonBll personBll) {
		this.personBll = personBll;
	}

	private IPersonBll personBll;

	public void showMsg() {
		this.personBll.show();
	}
}

package com.chzhao.springtest;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyConfig {
	@Bean
	public IPersonBll bll1() {
		return new PersonBll();
	}

	@Bean
	public App app1() {
		return new App(bll1());
	}
}
posted @ 2015-01-03 14:06  wardensky  阅读(188)  评论(0编辑  收藏  举报