//首先装载一个配置类
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
配置类这样写
@Configuration //等同与xml中的<beans>标签
@ComponentScan("com.pkg") //扫描包下的所有类
public class MyConfig {
}
茴字的另一种写法
@Configuration
public class MyConfig {
@Bean
public SomeService someService() {
return new SomeService();
}
}
@Component
@Scope("prototype")
//Singleton:表示该Bean是单例模式,在Spring容器中共享一个Bean的实例
//Prototype:每次调用都会新创建一个Bean的实例
//Request:这个是使用在Web中,给每一个http request新建一个Bean实例
//Session:这个同样是使用在Web中,表示给每一个http session新建一个Bean实例
public class SomeService {
....
}
//使用BEAN
SomeService bean = context.getBean(SomeService.class);
另各种注解
@Controller用于标注控制层组件
@Service用于标注业务层组件
@Repository用于标注数据访问组件,即DAO组件
@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
级别Controller> Service > Repository
Spring EL
@Configuration
@ComponentScan("org.sang")
@PropertySource(value = "some.properties",encoding = "UTF-8")
public class ELConfig {
//直接赋值
@Value("String value")
private String normal;
//使用java代码
@Value("#{T(java.lang.Math).random()*100}")
private double randomNumber;
//加载文本
@Value("file.txt")
private Resource testFile;
//some.properties 中的值
@Value("${ppp.value}")
private String su;
//代码
@Value("#{T(java.lang.Math).random()*100}")
private double randomNumber;
}
两种方法初始化和销毁
@Configuration
public class MyConfig {
@Bean(initMethod = "init",destroyMethod = "destroy")
BeanWayService beanWayService() {
return new BeanWayService();
}
@Bean
JSR250WayService jsr250WayService() {
return new JSR250WayService();
}
}
public class JSR250WayService {
@PostConstruct//构造方法执行之后执行
public void init() {
System.out.println("JSR250WayService-init()");
}
public JSR250WayService() {
System.out.println("JSR250WayService-构造方法");
}
@PreDestroy//销毁之前执行
public void destroy() {
System.out.println("JSR250WayService-destroy()");
}
}
@Profile设置初始化选项,类似的注解有@Conditional
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.getEnvironment().setActiveProfiles("prod");
context.register(ProfileConfig.class);
context.refresh();//需要刷新
@Configuration
public class ProfileConfig {
@Bean
@Profile("dev")
public DemoBean devDemoBean() {
return new DemoBean("dev");
}
@Bean
@Profile("prod")
public DemoBean prodDemoBean() {
return new DemoBean("prod");
}
}
//计划任务
@EnableScheduling//开启对计划任务的支持
@Scheduled(cron = "0 51 20 * * ?")
public void fixTimeExecution() {
.....
}
组合注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
@ComponentScan
public @interface MyConfiguration {
String[] value();
}
@Configuration
@ComponentScan("com.pkg")
等同于
@MyConfiguration("com.pkg")
文章来源http://blog.csdn.net/u012702547