Spring ApplicationContext

Posted by Adam on August 24, 2022
```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Service; import java.util.Arrays; @Service public class BeanListService { @Autowired private ApplicationContext applicationContext; /* * 列出所有的 Bean 名稱 */ public void listAllBeans() { String[] beanNames = applicationContext.getBeanDefinitionNames(); Arrays.sort(beanNames); System.out.println("List of Beans:"); for (String beanName : beanNames) { System.out.println(beanName); } } public void listAllDataSource() { // 使用 getBeansOfType 來獲取所有 DataSource.class 的實例 Map<String, DataSource> dataSourceBeans = context.getBeansOfType(DataSource.class); // 列印所有的 DataSource System.out.println("List of DataSource beans:"); dataSourceBeans.forEach((beanName, dataSource) -> { System.out.println("Bean Name: " + beanName); // 這裡你可以對每個 DataSource 執行需要的操作 }); } } ``` ```java import javax.management.MBeanInfo; import javax.management.MBeanServer; import javax.management.ObjectName; import java.lang.management.ManagementFactory; import java.util.Set; public class ListAllMBeans { public static void main(String[] args) { // 獲取平台 MBeanServer 實例 MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); // 獲取所有已知的 MBean ObjectName Set<ObjectName> objectNames = mBeanServer.queryNames(null, null); // 列出所有已知的 MBean System.out.println("List of Known MBeans:"); for (ObjectName objectName : objectNames) { try { MBeanInfo mBeanInfo = mBeanServer.getMBeanInfo(objectName); System.out.println("MBean: " + objectName); System.out.println(" - Class: " + mBeanInfo.getClassName()); // 你可以根據需要打印更多有關 MBean 的信息 } catch (Exception e) { e.printStackTrace(); } } } } ```