传统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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
Java类配置 基于@Configuration注解
@Bean可以对任何使用Spring @Component注解的类中的方法使用
@Configuration
public class BeanConfiguration {
@Bean
public Account account(){
return new Account("001001001");
}
@Bean
public User user(Account account){
return new User("张三",18,account);
}
@Bean
public User userNoAccount(){
return new User("张三",18,null);
}
}
基于注解
Spring提供进一步典型化注解:@Component,@Service,@Repository和 @Controller。@Component是任何Spring托管组件的通用构造型。 @Repository,@Service和@Controller是@Component针对更特定用例的专业化(分别在持久层,服务层和表示层)。因此,可以使用@Component,但是使用@Repository,@Service或者@Controller,能更好地适合于通过工具处理,或与切面进行关联,而且这些构造型注解在Spring框架的将来版本中还可以包含其他语义。