Spring 有几种配置方式?


1、xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="jackma" class="com.tyq.dto.User">
        <property name="name" value="jackma" />
        <property name="age" value="55" />
        <property name="dog" ref="jm" />
     </bean>

    <bean id="jm" class="com.tyq.dto.Dog">
        <property name="name" value="jack" />
        <property name="breed" value="金毛" />
        <property name="age" value="2" />
    </bean>
</beans>

2、基于注解的方式

项目越来越大,基于xml配置太麻烦,Spring 2.x时代提供了声明bean的注解。

(1)Bean的定义

@Component、@Controller、@Service、@Repository。

(2)Bean的注入

@Autowire


3、基于Java的方式

Spring 3.x以后,可以通过Java代码装配Bean。

@Configuration
public class DemoConfig {
    @Bean
    public User zs(){
        return new User();
    }
    @Bean
    public Dog dog(){
        return  new Dog();
    }
    @Bean  //两个狗
    public Dog haqi(){
        return new Dog();
    }
}
@Component("zs")
public class User {
    private String name;
    private int age;
    private Dog dog;

  //get,set方法略
}



0 0
讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
帮助