【Spring从入门到精通系列】一、spring基于配置和注解的开发方式介绍

spring分为基于配置的开发和注解的开发两种方式

基于配置的方式是这样的:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:context="http://www.springframework.org/schema/context"
     xsi:schemaLocation="http://www.springframework.org/schema/beans                                                      
     http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context                                                         
    http://www.springframework.org/schema/context/spring-context-4.3.xsd">
     
     <!-- 包扫描、只要标注了@Controller、@Service、@Component、@Repository -->
     <context:component-scan base-package="com.tl"></context:component-scan>
     
     <bean id="person" class="com.tl.bean.Person">
           <property name="name" value="张三"></property>
           <property name="age" value="18"></property>
     </bean>
     
</beans>

基于配置文件的方式,我们可以这样去获取bean

public class MainTest {
     public static void main(String[] args) {
           
             ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
             Person person1 = applicationContext.getBean("person", Person.class);
             System.out.println(person1);
           
     }
}

基于注解的方式如下:

@Configuration
告诉spring这是一个配置类

@Bean
给容器注册一个Bean

//配置类==配置文件
@Configuration  //告诉spring这是一个配置类
public class MainConfig {

     //给容器中注册一个Bean;类型为返回值的类型,id默认用方法名作为id
     @Bean(value = "person")
     public Person person01() {
           return new Person("23", "李四");
     }

}

基于注解的方式,我们可以这样去获取bean

public class MainTest {
     public static void main(String[] args) {
           ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
           System.out.println(applicationContext.getBean(Person.class));
     }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值