Springboot Springcloud
xml文件:aop (数据源、资源文件)
注解:ioc(业务逻辑开发)
Spring的Java配置方式是通过 @Configuration和 @Bean 这两个注解实现的:
1、@Configuration 作用于类上,相当于一个xml配置文件;
2、@Bean 作用于方法上,相当于xml配置中的<bean>;
@Configuration//通过该注解来表明该类是一个Spring的配置,相当于一个xml文件
@ComponentScan(basePackages = "cn.itcast.springboot.javaconfig") //配置扫描包
publicclass SpringConfig{
@Bean// 通过该注解来表明是一个Bean对象,相当于xml中的<bean>
public UserDAO getUserDAO(){
returnnew UserDAO(); // 直接new对象做演示
}
}
// 通过Java配置来实例化Spring容器
AnnotationConfigApplicationContext context = newAnnotationConfigApplicationContext(SpringConfig.class);
// 在Spring容器中获取Bean对象
UserService userService = context.getBean(UserService.class);
通过@PropertySource可以指定读取的配置文件,通过@Value注解获取值
@Configuration//通过该注解来表明该类是一个Spring的配置,相当于一个xml文件
@ComponentScan(basePackages = "cn.itcast.springboot.javaconfig") //配置扫描包
@PropertySource(value= {"classpath:jdbc.properties",“XXX”})
publicclass SpringConfig {
@Value("${jdbc.url}")
private String jdbcUrl;
@Bean// 通过该注解来表明是一个Bean对象,相当于xml中的<bean>
public UserDAO getUserDAO(){
returnnew UserDAO(); // 直接new对象做演示
}
}