Spring uses @Bean annotation

If you do not use Bean annotations, you need to configure the java classes that need to be injected in the Spring configuration file applicationContext.xml, such as

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

If you inject UserServiceImpl through the Bean method,
first, configure the package in applicationContext.xml to automatically scan the java classes that need to be injected

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

Then configure the @Configuration annotation before the java class that needs to be injected, and then write a method that returns the class, and configure the Bean annotation
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;
}

You're done

Guess you like

Origin blog.csdn.net/rj2017211811/article/details/108290703