main方法获取Spring 容器中的service方式

如下@service标注的类
@Service
public class EsIndexForPackageJobHandler extends IJobHandler {
}

使用main方法去获取service
public static void main(String[] args) {
   ApplicationContext ac = new ClassPathXmlApplicationContext("classpath*:applicationcontext*.xml");
   EsIndexForPackageJobHandler esIndexForPackageJobHandler = ac.getBean(EsIndexForPackageJobHandler.class);
   try {
      esIndexForPackageJobHandler.execute("11");
   } catch (Exception e) {
      e.printStackTrace();
   }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Spring纯注解方式实现,需要遵循以下步骤: 1. 在类上使用注解 @Component 或其派生注解(如@Service、@Repository等),标识该类为Spring容器的组件。 2. 如果该组件需要依赖其他组件,可以使用注解 @Autowired 或 @Resource 进行注入。 3. 如果需要配置组件的属性,可以使用注解 @Value 进行赋值。 4. 如果需要在启动时执行一些操作,可以使用注解 @PostConstruct 进行初始化。 下面是一个简单的示例代码: ```java @Component public class MyService { @Autowired private MyDao myDao; @Value("${myService.name}") private String name; @PostConstruct public void init() { System.out.println("MyService initialized"); } public void doSomething() { System.out.println("Hello, " + name); myDao.doSomething(); } } @Component public class MyDao { public void doSomething() { System.out.println("MyDao do something"); } } @Configuration @PropertySource("classpath:application.properties") public class AppConfig { @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } } public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); MyService myService = context.getBean(MyService.class); myService.doSomething(); } } ``` 这个示例,我们创建了两个组件 MyService 和 MyDao,MyService 依赖 MyDao,并且需要从属性配置文件读取 name 属性。我们使用注解 @Autowired 和 @Value 进行依赖注入和属性赋值,使用注解 @PostConstruct 进行初始化。我们还创建了一个配置类 AppConfig,用于读取属性配置文件。最后在 main 方法创建 AnnotationConfigApplicationContext 实例,并通过 context.getBean 获取 MyService 组件实例,并调用其 doSomething 方法

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值