简体   繁体   中英

Spring jdbctemplate best way

The spring.xml

<bean id="jdbcTemp" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="portalDataSource" />
</bean>

In class

    @Repository
public class DBUtil{

    private static final long serialVersionUID = -6203751104015962909L;
    @Autowired
    JdbcTemplate jdbcTemp;

    private static Logger log = Logger.getLogger("scmLogger");

    @Transactional(readOnly=true)
    public List<Map<String, Object>> getData(String qry, Object[] pAttr){
        log.debug("DBUtil.getData() qry "+qry);
        List<Map<String, Object>> vList =  new ArrayList<Map<String,Object>>(); 
        vList = jdbcTemp.queryForList(qry, pAttr);
        return vList;
    }

I would like to know if this "jdbcTemplate" is a singleton ie a single instance in my application. Is this the best way to use or any other way which will be better. Please suggest.

Regards

Adeeb

Though i am not a Spring pro, yes this jdbcTemplate is a singleton. Every bean managed by Spring is singleton unless specified otherwise. And there is nothing wrong with this usage.

When you define a bean in Spring, it has a singleton scope by default.

In your case, you are not defining a different scope so it's singleton.

http://www.tutorialspoint.com/spring/spring_bean_scopes.htm

Yes by default all beans in spring are singleton to make sure you can specify it in bean tag

<bean id="jdbcTemp" class="org.springframework.jdbc.core.JdbcTemplate" scope="singleton">
    <property name="dataSource" ref="portalDataSource" />
</bean>

in your class you are auto wiring it, and its the best way to do it. make sure your id in xml and instance variable name is same, in your code its correct jdbcTemp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM