Spring项目---如何实现bean加载时--方法被运行一次的效果呢?
下文笔者讲述Spring项目启动时---实现指定方法运行一次的效果
方式1:
使用@PostConstruct注解
当我们在方法上加上@PostConstruct注解
则可实现方法加载及运行
方式2:
继承 Applicationlistener< ContextRefreshedEvent >接口
然后实现onApplicationEvent()方法
方式3:
继承InitializingBean
实现方法 afterPropertiesSet方法
@Override
public void afterPropertiesSet() throws Exception {
/**业务方法*/
}
方式1:使用@PostConstruct注解
@Component
public class SystemInit {
@PostConstruct
public void init() {
System.out.println("=========初始化环境==============");
}
}
方式2
通过实现ApplicationListener< ContextRefreshedEvent >接口
实现onApplicationEvent()
@Service
public class SvnUserServiceImpl implements SvnUserService, ApplicationListener<ContextRefreshedEvent> {
private final Logger logger = LoggerFactory.getLogger(SvnUserServiceImpl.class);
@Value("${svn.passwd-httpd.path}")
private String passwdHttpd;
@Autowired
private SvnUserMapper svnUserMapper;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
// 保证只执行一次
if (event.getApplicationContext().getParent() == null) {
this.querySvnUserInfoInit();
}
}
}
方式3:继承InitializingBean
@Component
public class TestClass implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


