Loading

Spring注解Component使用

写个实体
//
等价于 在xml配置 <bean id="dog" class="com.rzk.pojo.Dog"/> @Component public class Dog { private String name; public String getDog() { return name; } @Value("狗子") public void setDog(String dog) { this.name = dog; } public void shout(){ System.out.println("狗叫"); } @Override public String toString() { return "Dog{" + "name='" + name + '\'' + '}'; } }
可以通过setName加上value 也可以在字段名上注入value ,在get的话不能
<?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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd"
>
    <!--指定要扫描的包,这个包下的注解会生效-->
    <context:component-scan base-package="com.rzk.pojo"/>
    <!--开启注解支持-->
    <context:annotation-config/>
</beans>

 

    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applocationContext.xml");
        Dog dog = context.getBean("dog", Dog.class);
        System.out.println(dog.getDog());
    }

 

posted @ 2020-03-31 15:30  Rzk  阅读(544)  评论(0编辑  收藏  举报