@Bean: 之前将类注入到IOC容器里的注解(@Component
@Repository
@Service
@Controller
)只能作用在类上,所以不能使用在第三方类上。@Bean是spring3之后出现的注解,作用在方法上,可以将一个方法的返回值作为bean对象存放在IOC容器里
思路:使用有参构造方式给属性赋值
方式一:直接调用已有方法
package com.ape.config;
import com.ape.controller.StudentController;
import com.ape.dao.StudentDao;
import com.ape.dao.StudentDaoImpl;
import com.ape.service.StudentService;
import com.ape.service.StudentServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
@Configuration
// 注解扫描器
@ComponentScan(basePackages = "com.ape")
// 引入外部文件
@PropertySource(value = "classpath:message.properties")
// 引入外部配置类
@Import(ApplicationContextConfig2.class)
public class ApplicationContextConfig {
/**
* 方式一 直接调用方法,使用有参构造来保持依赖关系
*
* @return
*/
@Bean
public StudentDao dao(){
return new StudentDaoImpl();
}
@Bean
public StudentService service(){
return new StudentServiceImpl(dao());
}
@Bean
public StudentController controller(){
return new StudentController(service());
}
}
方式二:把IOC容器里的Bean对象拿出来注入到参数中,还是使用有参构造
package com.ape.config;
import com.ape.controller.StudentController;
import com.ape.dao.StudentDao;
import com.ape.dao.StudentDaoImpl;
import com.ape.service.StudentService;
import com.ape.service.StudentServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
@Configuration
// 注解扫描器
@ComponentScan(basePackages = "com.ape")
// 引入外部文件
@PropertySource(value = "classpath:message.properties")
// 引入外部配置类
@Import(ApplicationContextConfig2.class)
public class ApplicationContextConfig {
/**
* 方式二,将已经注入IOC容器的对象拿出来作为参数
* 使用有参构造保持依赖关系
* 有没有@Autowired都可以
*
* @return
*/
@Bean
public StudentDao dao() {
return new StudentDaoImpl();
}
@Bean
public StudentService service(@Autowired StudentDao dao) {
return new StudentServiceImpl(dao);
}
@Bean
public StudentController controller(/*@Autowired*/ StudentService service) {
return new StudentController(service);
}
}