Spring 使用@Bean注解

不使用Bean注解的情况下需要在Spring配置文件applicationContext.xml里配置需要注入的java类,比如

 <bean id="userService" class="org.example.test.service.impl.UserServiceImpl">
   <property name="sqlSessionTemplate" ref="sqlSessionTemplate"></property>
 </bean>

如果通过Bean的方法注入UserServiceImpl,
首先,在applicationContext.xml配置自动扫描需要注入的java类所在包

<context:component-scan base-package="org.example.test.service.impl"/>-

然后在需要注入的java类前配置@Configuration注解,然后写一个返回该类的方法,配置Bean注解
UserServiceImpl.java

package org.example.test.service.impl;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Configuration
@Service("userService")
public class UserServiceImpl implements UserService {
    
    

    @Bean(initMethod = "init",destroyMethod = "destroy")
    public UserServiceImpl userServiceImpl(){
    
    
        return new UserServiceImpl();
    }
    public void init() {
    
    
        System.out.println("init ............");
    }
    public void destroy() {
    
    
        System.out.println(" destroy ...............");
    }
    @Resource
    private SqlSessionTemplate sqlSessionTemplate;
}

大功告成

猜你喜欢

转载自blog.csdn.net/rj2017211811/article/details/108290703