一.在程序中创建类SpringConfig类
@Configuration
@ComponentScan("MypackageName.ClassesName")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class, MybatisConfig.class})
public class SpringConfig {
}
注解第一行:@Configuration代表了原生注解xml文件
@ComponentScan("com.yulong")进行包扫描,注意引号里边不要留空,否则加载容器时会报出未找到bean名称的错误!
@PropertySource("classpath:jdbc.properties")对jdbc进行管理需创建jdbc管理类如下图:
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean
public DataSource dataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
}
@Import({JdbcConfig.class, MybatisConfig.class})则是进行bean的扫描如果在工具类上方添加@component在无需再使用!
二.写bean的接口
public interface AccountService {
void save(Account account);
void delete(Integer id);
void update(Account account);
List<Account> findAll();
Account findById(Integer id);
}
在接口的前提下写实现类impl
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
public void save(Account account) {
accountDao.save(account);
}
public void update(Account account){
accountDao.update(account);
}
public void delete(Integer id) {
accountDao.delete(id);
}
public Account findById(Integer id) {
return accountDao.findById(id);
}
public List<Account> findAll() {
return accountDao.findAll();
}
}
@service代表实现类为业务层
@@Autowired代表按类型进行依赖注入
三.Spring整合Mybatis
在项目中定义mybatisconfig工具类
public class MybatisConfig {
//定义bean,SqlSessionFactoryBean,用于产生SqlSessionFactory对象
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
ssfb.setTypeAliasesPackage("MypakegeName");
ssfb.setDataSource(dataSource);
return ssfb;
}
//定义bean,返回MapperScannerConfigurer对象
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setBasePackage("MyDaoPakageName");
return msc;
}
}
代码内的包名根据自己的进行更改
四.bean加载容器类
public class App {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
AccountService bean = ctx.getBean(AccountService.class);
Account account = bean.findById(2);
System.out.println(account);
}
}
第一行为加载容器,剩下的根据自己业务需求进行书写!