配置文件形式与注解形式的对比

首先,在com.demo.entity目录中创建两个类:Address 和 Student

注意:前提 idea 安装 Lombok 插件,maven 包安装 lombok 依赖

Address 类:

package com.demo.entity
@Data
class Address {
	String homeAddress;
	String schoolAddress;
}

Student 类:

package com.demo.entity
@Data
class Student {
	String stuNo;
	String stuName;
	String stuAge;
	String address;
}

一、配置文件(非注解形式)

建立 applicationContext.xml 文件,配置如下内容

<?xml version="1.0" encoding="GBK"?>  
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns="http://www.springframework.org/schema/beans"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">

    <bean id="student" class="com.demo.entity.Student">
        <property name="stuNo" value="1"></property>
        <property name="stuName" value="张三"></property>
        <property name="stuAge" value="23"></property>
        <property name="address" value="myaddress"></property>
    </bean> 
    
    <bean id="myaddress" class="com.demo.entity.Address">
        <property name="homeAddress" value="安徽"></property>
        <property name="schoolAddress" value="南京"></property>
    <bean>

</beans>  

创建 DemoTest.java 文件,获取bean

public class DemoTest {
	public static void main(String[] args) {
		// 创建 Spring 的 IOC 容器对象
		ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml ");
		// 从容器中获取 bean 实例(id 为 "student" 的 Student 对象)
		Student student = (Student)context.getBean("student");
	}
}

二、注解形式

@Configuration
class MyConfig{
	@Bean   // id="myStudent","myStudent" 是默认的方法名
	Student myStudent{
		Student student = new Student(1, "张三", 25);
		student.setAddress(new Address("安徽", "南京"));
		return student;
	}
}

创建 DemoTest.java 文件,获取bean

ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
Student stu = (Student)context.getBean("myStudent");
System.out.pringln(stu);

总结:
applicationContext.xml 等价于 注解 @Configuration
applicationContext.xml 里面的<bean>标签 等价于 @Bean

三、项目中的三层组件
SSM框架:

1、给三层组件分别加注解(@Controller、@Service、@Repository),就可以加进容器中
2、将注解所在包纳入 ioc 扫描器(ComponentScan)

SSM框架中 配置文件与注解形式(对比于SpringBoot)

a、Controller 层:
配置文件形式

 <context: conponent-scan base-package="com.demo.controller"> // 该com.demo.controller 表示目录
   // 各种 bean 标签,即方法表示
   </context>

注解形式

package com.demo.controller;

@Controller
class DemoController{
	// 各种方法
}

b、service层:
配置文件形式

 <context: conponent-scan base-package="com.demo.dao"> // 该com.demo.service表示目录
   // 各种 bean 标签,即方法表示
   </context>

注解形式

package com.demo.service;

@Service
class DemoService{
	// 各种方法,即对应配置文件中的 bean 标签
}

其他 dao 层等等同理

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值