两种方式初始化:
1、配置文件 init-method
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http:///schema/beans"
xmlns:xsi="http:///2001/XMLSchema-instance"
xsi:schemaLocation="http:///schema/beans http:///schema/beans/spring-beans.xsd">
<bean id="roleService" class=".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:///schema/beans"
xmlns:xsi="http:///2001/XMLSchema-instance"
xmlns:context="http:///schema/context"
xsi:schemaLocation="http:///schema/beans http:///schema/beans/spring-beans.xsd http:///schema/context https:///schema/context/spring-context.xsd">
<context:component-scan base-package=""/>
</beans>
运行结果
RoleService 构造方法被初始化了....
RoleService test()....
Disconnected from the target VM, address: '127.0.0.1:53158', transport: 'socket'
Process finished with exit code 0