What are the ways to inject Beans into IOC containers in Spring?

"We all need to learn to be strong, because life will not stop because of our weakness." - "The Great Gatsby"

Table of contents

1. XML configuration file-based method

2. Annotation-based approach

3. Method based on Java configuration class


1. XML configuration file-based method

Use the <bean> tag in the XML configuration file to define the Bean, and inject the Bean into the IOC container through attribute injection. For example:

<bean id="userService" class="com.example.UserService">
    <property name="userDao" ref="userDao"/>
</bean>

<bean id="userDao" class="com.example.UserDao"/>

2. Annotation-based approach

Use annotations to annotate beans, and inject beans into the IOC container through @Autowired or @Resource annotations. For example:

@Service
public class UserService {
    @Autowired
    private UserDao userDao;
}

@Repository
public class UserDao {}

3. Method based on Java configuration class

Use the @Configuration annotation to annotate the Java configuration class, use the @Bean annotation to define the Bean in the configuration class, and inject the Bean into the IOC container through the @Autowired or @Resource annotation. For example:

@Configuration
public class AppConfig {
    @Bean
    public UserService userService() {
        UserService userService = new UserService();
        userService.setUserDao(userDao());
        return userService;
    }

    @Bean
    public UserDao userDao() {
        return new UserDao();
    }
}

Guess you like

Origin blog.csdn.net/qq_61902168/article/details/131124951