Solon Web 开发,十四、与Spring、Jsr330的常用注解对比
1、注解对比
Solon 3.0 | Springboot 2.7.16 / 3.3.2 | 说明 |
---|---|---|
@Inject * | @Autowired | 注入Bean(by type) |
@Inject("name") | @Qualifier+@Autowired | 注入Bean(by name) |
@Inject("${name}") | @Value("${name}") + @ConfigurationProperties(prefix="name") | 注入配置 |
@Singleton | @Scope(“singleton”) | 单例(Solon 默认是单例) |
@Singleton(false) | @Scope(“prototype”) | 非单例 |
@Import | @Import + @ComponentScan | 导入组件(一般加在启动类上) |
@Import | @PropertySource | 导入属性源(一般加在启动类上) |
@Configuration | @Configuration | 配置类 |
@Bean | @Bean | 配置Bean |
@Condition | @ConditionalOnClass + @ConditionalOnProperty ... | 配置条件 |
@Component | @Component,@Service,@Dao,@Repository | 托管组件 |
@Import | @TestPropertySource | 导入测试属性源 |
@Rollback | @TestRollback | 执行测试回滚 |
LifecycleBean | InitializingBean + DisposableBean | 组件初始化和销毁 |
Solon {{solon-version}} | Java EE / Jakarta | |
LifecycleBean::start 或 @Init 注解 |
@PostConstruct | 组件初始化 |
LifecycleBean::stop 或 @Destroy 注解 |
@PreDestroy | 组件销毁 |
- 注1:Method@Bean,只执行一次(只在 @Configuration 里有效)
- 注2:@Inject 的参数注入,只在 Method@Bean 和 Constructor 上有效
- 注3:@Inject 的类注入,只在 @Configuration类 上有效
- 注4:@Import 只在 启动类上 或者 @Configuration类 上有效
2、部分用例说明
Solon 强调有节制的注解使用,尤其对于增加处理链路的操会比较节制。
- @Component(组件托管:基于 name 或者 类型;且只记录第一次的注册)
@Component
public class UserService{
@Db("db1") //@Db为第三方扩展的注入注解
BaseMapper<User> mapper;
UserModel getUser(long puid){
return db1.selectById(puid);
}
}
/* @Component("userService")
public class UserService{
@Db("db1")
BaseMapper<User> mapper;
UserModel getUser(long puid){
return db1.selectById(puid);
}
} */
- @Controller
@Singleton(false) //非单例注解
@Controller
public class UserController{
@Inject("${message.notnull}")
String message;
@Inject
UserService userService
@Mapping("/user/{puid}")
public Object user(Long puid){
if(puid == null){
return message;
}
return userService.getUser(puid);
}
}
- @Configuration
@Configuration
public class Config {
@Bean("db1")
public DataSource db1(@Inject("${test.db1}") HikariDataSource ds) {
return ds;
}
}
//系统异常监听(这个系统会发的,还可以监听不同的异常)
//
@Configuration
public class ThrowableListener implements EventListener<Throwable> {
WaterLogger log = new WaterLogger("rock_log");
@Override
public void onEvent(Throwable err) {
Context ctx = Context.current();
if (ctx != null) {
String _in = ONode.stringify(ctx.paramMap());
log.error(ctx.path(), _in, err);
}
}
}