利用spring实现服务启动就自动执行某些操作的2种方式

本文探讨了Spring中Bean的两种初始化方式:使用init-method属性和实现InitializingBean接口。同时,详细介绍了如何解决属性注入失败的问题,确保Bean的正确配置。

第一种方式,用bean的init-method属性

<bean class="com.emax.paycenter.log.LogBridge" init-method="init"></bean>

第二种方式,实现InitializingBean接口

@Component
public class TJUnionAgentPayNotifyTCPServer implements InitializingBean {

    private static Logger logger = LogManager.getLogger();

    @Autowired
    private ThreadPoolTaskExecutor tjunionNotifyTaskExecutor;

    @Override
    public void afterPropertiesSet() throws Exception {
        logger.info("异步线程开启TCP侦听...");
//        new Thread() {
//            public void run() {
//                openTJUnionAgentPayNotifyTCPServer();
//            }
//        }.start();
    }
}

 不过,这种在class名上声明@Component或@Service注解,当启动服务后,发现afterPropertiesSet方法被重复执行两次。寻不得果。

只好不用注解,改用声明bean的方式,spring默认每个Bean的作用域都是单例。

<bean class="com.emaxcard.tcpserver.TJUnionAgentPayNotifyTCPServer">
    <property name="tjunionNotifyTaskExecutor" ref="tjunionNotifyTaskExecutor"></property>
</bean>

 

这种情况下,要注意,给bean的私有属性赋值时,这个属性要有公共的set方法,以让spring可以找到。

2018-11-30 10:28:03,301 ERROR [main] (ContextLoader.java:351) - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.emaxcard.tcpserver.TJUnionAgentPayNotifyTCPServer#0' defined in class path resource [spring.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'tjunionNotifyTaskExecutor' of bean class [com.emaxcard.tcpserver.TJUnionAgentPayNotifyTCPServer]: Bean property 'tjunionNotifyTaskExecutor' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

 

public class TJUnionAgentPayNotifyTCPServer implements InitializingBean {

    private static Logger logger = LogManager.getLogger();

    private ThreadPoolTaskExecutor tjunionNotifyTaskExecutor;

    public void setTjunionNotifyTaskExecutor(ThreadPoolTaskExecutor tjunionNotifyTaskExecutor) {
        this.tjunionNotifyTaskExecutor = tjunionNotifyTaskExecutor;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        logger.info("异步线程开启TCP侦听...");
//        new Thread() {
//            public void run() {
//                openTJUnionAgentPayNotifyTCPServer();
//            }
//        }.start();
    }
}

 

转载于:https://www.cnblogs.com/buguge/p/10042928.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值