spring框架学习笔记
IOC容器
整个项目就是由各种组件搭建而成的:
组件可以完全交给Spring 框架进行管理,Spring框架替代了程序员原有的new对象和对象属性赋值动作等!
Spring IoC 容器,负责实例化、配置和组装 bean(组件)。容器通过读取配置元数据来获取有关要实例化、配置和组装组件的指令。配置元数据以 XML、Java 注解或 Java 代码形式表现。它允许表达组成应用程序的组件以及这些组件之间丰富的相互依赖关系。
创建一个项目得写一个ioc类配置
/*开头得写上这三个标签
1.@ComponentScan("org.hufeng"):这个注解用于指定 Spring 应该在哪些包中查找带有 @Component、@Service、@Repository 和 @Controller 等注解的类,并将这些类注册为 Spring 应用上下文中的 Bean。在这个例子中,Spring 将会扫描 "org.hufeng" 包及其子包。
2.@Configuration:这个注解表明该类是一个配置类,它定义了 Spring 应用上下文的 Bean 定义。配置类是 Spring 的一种现代替代 XML 配置文件的方式。
3.@PropertySource("classpath:jdbc.properties"):这个注解用于指定属性文件的位置,这些属性可以在 Spring 应用上下文中使用。在这个例子中,属性文件 jdbc.properties 位于类路径(classpath)上。这些属性可以使用 @Value 注解注入到 Bean 中。
*/
@ComponentScan("org.hufeng")
@Configuration
@PropertySource("classpath:jdbc.properties")
public class JavaConfig {
@Bean//需要打上Bean标签标识装在IOC容器
public DataSource dataSource(
@Value("${hufeng.driver}")String driver,
@Value("${hufeng.url}")String url,
@Value("${hufeng.username}")String username,
@Value("${hufeng.password}")String password){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource){
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
return jdbcTemplate;
}
}
Dao包
// 接口
public interface StudentDao {
List<Student> queryAll();
}
//类
@Repository
public class StudentDaoImpl implements StudentDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public List<Student> queryAll() {
String sql = "select * from students";
List<Student> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Student.class));
//Student.class是一定要注意写的,因为这是将查询结果映射为 Student 类型的对象列表。
return query;
}
}
Service包
// 接口
public interface StudentService {
List<Student> All();
}
//类
@Service
public class StudentServiceImpl implements StudentService{
@Autowired
private StudentDaoImpl studentDao;
@Override
public List<Student> All() {
List<Student> students = studentDao.queryAll();
return students;
}
}
Controlle包
@Controller
public class StudentController {
@Autowired
private StudentServiceImpl studentService;
public void find(){
List<Student> all = studentService.All();
System.out.println(all);
}
}
测试类
public class test1 {
@Test
public void Test1(){
AnnotationConfigApplicationContext applicationContext =
new AnnotationConfigApplicationContext(JavaConfig.class);
StudentController bean = applicationContext.getBean(StudentController.class);
bean.find();
applicationContext.close();
}
}
这就是ioc框架的使用流程,需要注意的是添加标签
1.写ioc配置类,注意添加三个标签
2.先写dao 再写service 最后写controlle写的时候注意@Bean标签和@Autowired标签
se();
}
}
这就是ioc框架的使用流程,需要注意的是添加标签
1.写ioc配置类,注意添加三个标签
2.先写dao 再写service 最后写controlle写的时候注意@Bean标签和@Autowired标签
装配用@Bean,使用用@Autowired