bean注入demo

本文通过一个Java示例介绍了如何使用反射和Introspector来获取类的方法和属性信息,并展示了如何设置属性值。
public class TestUser {
	
public static void main(String args [] ) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
                Class bean = null;
		try {
			bean = Class.forName("inject.User");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("can't find class");
			e.printStackTrace();
		}  
		BeanInfo info = null;
		try {
			info = Introspector.getBeanInfo(bean);
		} catch (IntrospectionException e) {
			// TODO Auto-generated catch block
			System.out.println("get the information of the class");
			e.printStackTrace();
		}
		// 遍历指定类的方法
		MethodDescriptor[] methods = info.getMethodDescriptors();  
        for (int i = 0; i < methods.length; i++) {  
            System.out.println("方法:"+methods[i].getDisplayName());  
        }  
        // 遍历指定类的属性  
        PropertyDescriptor[] propertys = info.getPropertyDescriptors();  
        for (int j = 0; j < propertys.length; j++) {  
            System.out.println("属性:"+propertys[j].getName());  
        }  
        
        Object obj = bean.newInstance();
        Method mSet = null;  
        for(int k = 0; k < propertys.length; k++){
        	mSet = propertys[k].getWriteMethod();
        	if(propertys[k].getName().equalsIgnoreCase("name")){
        		mSet.invoke(obj, "mutou");
        		continue;
        	}
        	if(propertys[k].getName().equalsIgnoreCase("password")){
        		mSet.invoke(obj, "mutou_password");
        		continue;
        	}
        }
        User user = (User)obj;
        System.out.println(user.getName());
        System.out.println(user.getPassword());   
	}
}
<pre name="code" class="java">public class User {
	
	String name;
	
	String password;
    //setter getter no paragram constructor
}

输出

方法:notify
方法:wait
方法:setPassword
方法:getClass
方法:getName
属性:class
属性:name
属性:password
mutou
mutou_password


参考资料 http://blog.youkuaiyun.com/zhikun518/article/details/7185499

<think>好的,我需要回答用户关于如何在Spring Boot中使用@Bean注解注入Mapper类的问题。用户还希望有示例代码,并且需要结合他们提供的引用内容。首先,我要回顾一下用户提供的引用,看看是否有相关信息可以引用。 引用3和5提到了@MapperScan的作用,可以自动扫描Mapper接口并生成实现类。但用户的问题是关于使用@Bean手动注入Mapper类,这可能涉及到通过@Bean方法显式创建Mapper实例。 接下来,我需要回忆Spring Boot中MyBatis的常见配置方法。通常,使用@MapperScan可以让Spring自动注册Mapper接口的代理类。但如果要手动注入,可能需要结合SqlSessionTemplate或SqlSessionFactory来创建Mapper实例。 例如,可以在配置类中定义一个@Bean方法,使用SqlSessionTemplate的getMapper方法获取Mapper接口的实现,然后将其注册为Bean。这样,当其他组件需要注入该Mapper时,Spring会使用这个手动定义的Bean。 需要注意的是,如果同时使用@MapperScan和手动@Bean注入同一个Mapper接口,可能会导致多个Bean的冲突。这时候可能需要用@Primary来指定优先使用的Bean,如引用1提到的。 现在需要编写一个示例代码,展示如何通过@Bean注解注入Mapper类。同时,需要引用相关的引用内容,比如引用3和5关于@MapperScan的作用,以及引用1关于@Primary的使用。 可能的结构是: 1. 引入依赖(如MyBatis-Spring-Boot-Starter) 2. 创建Mapper接口 3. 创建配置类,使用@Bean注解定义Mapper Bean 4. 在Service中注入Mapper 同时,需要指出可能出现的冲突及解决方法,比如使用@Primary。 检查是否有遗漏点,比如是否需要配置SqlSessionFactory或者数据源,但通常Spring Boot会自动配置这些,所以示例中可以简化。 最后,生成相关问题,比如如何解决多个Bean冲突、@Bean和@MapperScan的区别等。</think>在 Spring Boot 中,可以通过 `@Bean` 注解手动将 Mapper 类注入 Spring 容器,通常需要结合 `SqlSessionTemplate` 或 `MapperFactoryBean` 来实现。以下是具体示例和步骤: --- ### 1. 通过 `@Bean` 注解注入 Mapper 的示例 ```java @Configuration public class MyBatisConfig { @Autowired private SqlSessionTemplate sqlSessionTemplate; @Bean public UserMapper userMapper() { return sqlSessionTemplate.getMapper(UserMapper.class); } } ``` #### 说明: 1. **依赖注入 `SqlSessionTemplate`** Spring Boot 自动配置会生成 `SqlSessionTemplate` 实例,用于执行 MyBatis 操作[^5]。 2. **定义 `@Bean` 方法** 通过 `sqlSessionTemplate.getMapper()` 获取 Mapper 接口的代理实现类,并将其注册为 Spring Bean。 3. **使用 Mapper** 在其他组件中可直接注入: ```java @Service public class UserService { @Autowired private UserMapper userMapper; // 直接使用注入Bean } ``` --- ### 2. 与 `@MapperScan` 的对比 - **`@Bean` 手动注入**:适用于需要自定义 Mapper 实例的场景(如动态数据源切换)。 - **`@MapperScan` 自动扫描**:更简洁,推荐默认使用(自动扫描指定包下的 Mapper 接口)[^3]。 --- ### 3. 解决 Bean 冲突问题 如果同时使用 `@MapperScan` 和 `@Bean` 注入同一 Mapper 接口,会导致重复 Bean 定义。此时可通过 `@Primary` 指定优先级: ```java @Bean @Primary // 声明为默认优先注入Bean public UserMapper userMapper() { return sqlSessionTemplate.getMapper(UserMapper.class); } ``` 这样 Spring 会优先选择手动定义的 Bean[^1]。 --- ### 4. 完整项目结构示例 ``` src/ ├── main/ │ ├── java/ │ │ ├── com.example.demo/ │ │ │ ├── config/MyBatisConfig.java // 包含 @Bean 定义 │ │ │ ├── mapper/UserMapper.java // Mapper 接口 │ │ │ └── service/UserService.java // 使用 Mapper 的 Service │ └── resources/ │ └── application.properties // 数据源配置 ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值