1. 首页
  2. 软件开发
  3. Spring——IOC基于注解管理Bean的全注解开发详细步骤(无需XML配置文件)

Spring——IOC基于注解管理Bean的全注解开发详细步骤(无需XML配置文件)

  • 发布于 2024-08-17
  • 0 次阅读

全注解开发是指完全基于注解而不需要XML配置文件来管理Bean。在Spring框架中,可以通过使用 @ComponentScan 和 @Configuration 注解来实现全注解开发。

1. 创建一个简单的UserService类和UserDao类

package com.example;

public interface UserDao {
   
    void save();
}

package com.example;

import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {
   
    @Override
    public void save() {
   
        System.out.println("Saving user data...");
    }
}
package com.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
   
    private UserDao userDao;

    @Autowired
    public void setUserDao(UserDao userDao) {
   
        this.userDao = userDao;
    }

    public void process() {
   
        userDao.save();
    }
}

2. 创建一个配置类AppConfig.java,用于启用组件扫描

package com.example;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {
   
}

在这个配置类中, @Configuration 注解表示这是一个配置类, @ComponentScan 注解用于指定要扫描的包路径,Spring容器会自动扫描这些包下带有特定注解的类。

3. 创建一个主应用程序类


package com.example;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MainApp {
   
    public static void main(String[] args) {
   
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

        UserService userService = context.getBean(UserService.class);
        userService.process();

        context.close();
    }
}

在主应用程序类中,创建了一个 AnnotationConfigApplicationContext 对象并传入配置类 AppConfig.class ,然后通过 getBean 方法获取 UserService 的实例,并调用其方法。

原文链接: https://blog.csdn.net/2401_82884096/article/details/136976810