欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-03-31 23:00:25
第一种方式,用bean的init-method属性 第二种方式,实现InitializingBean接口 不过,这种在class名上声明@Component或@Service注解,当启动服务后,发现afterPropertiesSet方法被重复执行两次。寻不得果。 只好不用注解,改用声明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();
    }
}