利用spring實現服務啟動就自動執行某些操作的2種方式


第一種方式,用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();
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM