本文共 2228 字,大约阅读时间需要 7 分钟。
@Component,@Service,@Repository,@Controller
注解在一个类上之后,这个类也成为spring容器中的bean,使用@Bean注解也是,感觉使用@Bean注解是不是更麻烦呢?
既然效果是等同的,那什么时候使用@Bean什么时候使用@Component,@Service,@Repository,@Controller
系列呢?
这个原则就和我们当初混用xml配置和@Component,@Service,@Repository,@Controller
时候一样:系统的全局配置(数据库配置,spring mvc配置,spring security配置等)使用java config(xml),业务相关的bean使用@Component,@Service,@Repository,@Controller
系列。
在后面我们讲到一些全局配置的时候我们就会使用Spring的java config
wisely.word = World
package com.wisely.javaconfig;public class DemoService { private String word; public String getWord() { return word; } public void setWord(String word) { this.word = word; } public String sayHello(){ return "Hello "+this.word; }}
package com.wisely.javaconfig;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.PropertySource;import org.springframework.core.env.Environment;@Configuration //声明是一个配置类@PropertySource("com/wisely/javaconfig/test.properties")public class DemoConfig { @Bean //声明是一个bean public DemoService demoBean(Environment environment){ DemoService demoService = new DemoService(); demoService.setWord(environment.getProperty("wisely.word")); return demoService; }}
package com.wisely.javaconfig;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Main { public static void main(String[] args) { //设定此包下的类被注册成spring的bean, //包含@Configuration,@Component,@Service,@Repository,@Controller AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.wisely.javaconfig"); DemoService demoService = context.getBean(DemoService.class); System.out.println(demoService.sayHello()); context.close(); }}
输出结果:Hello World
转载地址:http://jjcpi.baihongyu.com/