程序员社区

Spring注解开发(创建对象)

@Component:用于创建对象

@Component:用于把当前类存入Spring容器中
value:用于指定bean的id,不写时,默认是当前类名的首字母小写
@Component(value=“accountService”)

实体类:

@Component(value="accountService")
public class AccountServiceImpl implements AccountService{
    public void saveAccount() {
        System.out.println("sevice方法被执行了....");
    }
}

bean.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"
       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.xsd">
	<!--用于指定要扫描的包-->
    <context:component-scan base-package="com.hh">
    </context:component-scan>
</beans>

测试类:

public class Client {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean.xml");
        AccountService service =
                context.getBean("accountService", AccountService.class);
        System.out.println(service);
    }
}

@Repository
@Service
@Controller
以上三个注解和@Component作用相同

赞(0) 打赏
未经允许不得转载:IDEA激活码 » Spring注解开发(创建对象)

相关推荐

  • 暂无文章

一个分享Java & Python知识的社区