Solon2 开发之IoC,九、自定义注解开发汇总
1、定义构建能力注解,比如@Controller
注解类:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Controller {
}
注解类能力注册:
//注册 @Controller 构建器
Solon.context().beanBuilderAdd(Controller.class, (clz, bw, anno) -> {
//内部实现,可参考项目源码
new HandlerLoader(bw).load(Solon.app());
});
应用示例:
@Controller
public class DemoController{
@Mapping("/hello")
public String hello(){
return "Hello world!";
}
}
2、定义字段或参数注入能力的注解,比如@Inject
注解类:
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Inject {
String value() default "";
boolean required() default true;
boolean autoRefreshed() default false;
}
注解类能力注册:
//注册 @Inject 注入器
Solon.context().beanInjectorAdd(Inject.class, ((fwT, anno) -> {
//内部实现,可参考项目源码
beanInject(fwT, anno.value(), anno.autoRefreshed());
}));
应用示例:
@Service
public class DemoService{
//注入字段
@Inject
UserMapper userMapper;
}
@Configuration
public class DemoConfig{
//注入到参数。只支持与:@Bean 配合
@Bean
public DataSource ds(@Inject("${db1}") HikariDataSource ds){
return ds;
}
}
3、定义函数拦截能力的注解,比如@Tran
注解类:
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Tran {
TranPolicy policy() default TranPolicy.required;
TranIsolation isolation() default TranIsolation.unspecified;
boolean readOnly() default false;
}
注解类能力注册:
//内部实现,可参考项目源码
Solon.context().beanAroundAdd(Tran.class, new TranInterceptor(), 120);
应用示例:
@Service
public class DemoService{
//注入字段
@Inject
UserMapper userMapper;
@Tran
public void addUser(User user){
userMapper.add(user);
}
}
4、定义函数提取能力的注解,比如:@CloudJob
注解类:
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CloudJob {
@Alias("name")
String value() default "";
@Alias("value")
String name() default "";
String cron7x() default "";
String description() default "";
}
注解类能力注册:
//内部实现,可参考项目源码
Solon.context().beanExtractorAdd(CloudJob.class, CloudJobExtractor.instance);
应用示例:
@Component
public class JobController{
@CloudJob(name="user.stat", cron7x="0 0/1 * * * ? *")
public void userStatJob(){
//...
}
}