Spring-02 Java配置实现IOC

时间:2023-03-09 20:12:28
Spring-02 Java配置实现IOC

Java配置

  • Spring4推荐使用java配置实现IOC
  • Spring boot也推荐采用java配置实现IOC
  • 在实际项目中,一般采用注解配置业务bean,全局配置使用Java配置。

Java配置使用的注解

  • @Configuration:声明当前类为配置类,配置类等效于spring配置xml文件。
  • @Bean:声明在方法上,方法返回值为Bean。

示例代码

特点:dao和service层不再使用注解

dao的代码

package com.etc.dao;

import org.springframework.stereotype.Repository;

public class EntityDao {

	public String getData(){
return "get data from database";
}
}

  

service的代码

package com.etc.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.etc.dao.EntityDao; public class EntityService { private EntityDao entityDao; public String getData(){
return entityDao.getData();
} }

 

Java配置类的代码

package com.etc.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import com.etc.dao.EntityDao;
import com.etc.service.EntityService; /** 声明当前类是一个配置类 ,在该类中定义bean*/
@Configuration
public class JavaConfig { /**获取dao的bean*/
@Bean
public EntityDao entityDao(){
return new EntityDao();
} /**获取service的bean*/
// @Bean
// public EntityService entityService(){
// EntityService entityService=new EntityService();
// entityService.setEntityDao(entityDao());
// return entityService;
// } /**获取serveice的bean时,通过方法参数注入bean*/
@Bean
public EntityService entityService(EntityDao entityDao){
EntityService entityService=new EntityService();
entityService.setEntityDao(entityDao);
return entityService;
} }

  

测试类代码

package com.etc.test;

import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.etc.config.DiConfig;
import com.etc.config.JavaConfig;
import com.etc.service.EntityService; public class TestClass { /**测试使用注解实现IOC*/
public void test1() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
DiConfig.class);
EntityService es = context.getBean(EntityService.class);
System.out.println(es.getData());
context.close();
} /**测试使用Java配置实现IOC*/
@Test
public void test2(){
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
JavaConfig.class);
EntityService es = context.getBean(EntityService.class);
System.out.println(es.getData());
} }

  

测试结果

get data from database