一、首先,需要xml中进行少量的配置来启动Java配置:
- <?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:aop="http://www.springframework.org/schema/aop"
- xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
- 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.2.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
- <context:component-scan base-package="SpringStudy.Model">
- </context:component-scan>
- </beans>
二、定义一个配置类
用@Configuration注解该类,等价 与XML中配置beans;用@Bean标注方法等价于XML中配置bean。
代码如下:
- package SpringStudy;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import SpringStudy.Model.Counter;
- import SpringStudy.Model.Piano;
- @Configuration
- public class SpringConfig {
- @Bean
- public Piano piano(){
- return new Piano();
- }
- @Bean(name = "counter")
- public Counter counter(){
- return new Counter(12,"Shake it Off",piano());
- }
- }