两种方式初始化:
1、配置文件 init-method
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="roleService" class="com.xxx.service.RoleService" init-method="init"/> </beans>
*/ public class RoleService { public RoleService() { System.out.println("RoleService 构造方法被初始化了...."); } public void test(){ System.out.println("RoleService test()...."); } public void init(){ System.out.println("RoleService init()....."); } }
运行结果
RoleService 构造方法被初始化了.... RoleService init()..... RoleService test().... Disconnected from the target VM, address: '127.0.0.1:53138', transport: 'socket' Process finished with exit code 0
2、实现接口 InitializingBean
@Service public class RoleService implements InitializingBean { public RoleService() { System.out.println("RoleService 构造方法被初始化了...."); } public void test(){ System.out.println("RoleService test()...."); } @Override public void afterPropertiesSet() throws Exception { System.out.println("RoleService afterPropertiesSet()....."); } }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.xxx"/> </beans>
运行结果
RoleService 构造方法被初始化了.... RoleService test().... Disconnected from the target VM, address: '127.0.0.1:53158', transport: 'socket' Process finished with exit code 0